11.2. Comparing Tuples¶
The comparison operators can be used with tuples and other sequences. Python starts by comparing the first element from each sequence. If they are equal, it compares the next element of each, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they’re really big).
(0, 1, 2) < (0, 3, 4) >>> True (0, 1, 2000000) < (0, 3, 4) >>> True
sort() is a list method that can be helpful when managing a list of tuples. When sorting, it compares the
first element of each tuple, but in the case of a tie, it compares their second elements, and
Combining these tools leads to a very common, and widely applicable sorting process called DSU. DSU is short for:
Decorate a sequence by building a list of tuples with one or more sort metrics preceding the elements from the sequence.
Sort the list of tuples using Python’s built-in
Undecorate by extracting the sorted elements of the sequence.
For example, suppose you have a list of words and you want to sort them from longest to shortest:
Let’s walk through the DSU process:
The first loop decorates by building a list of tuples, where each tuple is a word preceded by its length.
sort sorts by comparing the first element of each tuple (length) first. It only
considers the second element, alphabetical order, to break ties. The keyword argument
sort to go in decreasing
order, meaning that longer words will be first in the sorted list and that if two words are
the same length, the one that comes last in alphabetical order will appear before the other.
Finally, the second loop undecorates by traversing the list of tuples and adding the sorted words to a list.
The output of the program is as follows:
['yonder', 'window', 'breaks', 'light', 'what', 'soft', 'but', 'in']
Of course, the line loses much of its poetic impact when turned into a Python list and sorted in descending word length order.
Move the code blocks around to create a program that sorts the words in word_list by length from longest to shortest and adds them to sorted_word_list. Hint: remember DSU!