Sorting by Another Rule
So far, Python has compared the elements themselves: numbers by their size, texts by their letters. Sometimes you need another rule, for example words from the shortest to the longest. For that, sorted() and .sort() have the parameter key. You give it a function, and Python sorts the elements by what the function returns for each of them:
words = ["cherry", "fig", "banana", "kiwi"]
print(sorted(words, key=len))['fig', 'kiwi', 'cherry', 'banana']Python calls len() on each element: len("cherry") is 6, len("fig") is 3, len("banana") is 6 and len("kiwi") is 4. Then it sorts the elements by these numbers, their keys: 3, 4, 6, 6. (This key has nothing to do with the keys of a dictionary: it's what an element is compared by.) The list it returns holds the words themselves, not the numbers. "cherry" and "banana" have the same key, and elements with the same key keep the order they had: cherry was before banana, so it stays before it.
Notice that the function is written without parentheses: key=len. You don't call it yourself. You give sorted() the function, and sorted() calls it on each element. With parentheses, Python would call len() right away, with nothing in it: key=len() ends with TypeError: len() takes exactly one argument (0 given).
A key is also how you sort texts without caring about uppercase and lowercase. You know the method .lower() from Working with Text. It belongs to texts, whose type is str, and written as str.lower, it's a function you can give to key: str.lower("Zoe") is "zoe".
names = ["adam", "Zoe", "Bob"]
print(sorted(names))
print(sorted(names, key=str.lower))['Bob', 'Zoe', 'adam']
['adam', 'Bob', 'Zoe']Python compares the lowercase versions, but the list it returns has the names as they were written. Letters with accents stay after z, though: str.lower("Émile") is "émile", which still comes after "zoe".
key and reverse work together too: sorted(words, key=len, reverse=True) puts the longest words first.
Instructions
- 1
Different people typed the cities, some with a capital letter and some without, so
sorted()putsamsterdamandberlinat the end. Change theprint()so that it sorts the cities without caring about uppercase and lowercase:['amsterdam', 'berlin', 'Budapest', 'Paris', 'Rome']. Leave the line with the cities as it is: the exercise also runs your program with other cities. - 2
Below, print the cities sorted from the shortest name to the longest:
['Rome', 'Paris', 'berlin', 'Budapest', 'amsterdam'].