Summary
In this lesson, you learned that:
sorted(values)returns a new list with the values from the smallest to the largest, and leaves the original as it was. It takes anything aforloop can go through (a list, a tuple, a set, a dictionary's keys) and always returns a list. That's how you print a set in the same order every time:print(sorted(guests)).- Texts are compared letter by letter, by the codes of their letters: uppercase letters come before lowercase ones (
"Zoe"before"adam"), and letters with accents afterz. Numbers written as text are sorted as text, so convert them withint()first. values.sort()sorts the list itself and returnsNone. Never store what it returns: afternames = names.sort(), the list is gone. Only lists have.sort().reverse=Truesorts from the largest.sorted(scores, reverse=True)[:3]are the three highest scores.keytakes a function, written without parentheses. Python calls it on each element and sorts the elements by what it returns:key=lensorts by length,key=str.lowerwithout caring about uppercase and lowercase. Elements with the same key keep their order.- The key function can be your own:
by_score(player), which returnsplayer[1], sorts a list of tuples by their second elements, andsorted(scores.items(), key=by_score)sorts the pairs of a dictionary by their values. max()andmin()takekeytoo, and return the element with the largest or the smallest key:max(words, key=len)is the longest word.
Now practice it on the results of a long jump competition. In the next lesson, List Comprehensions, you'll learn to build a new list from another one in a single line, for example the lengths of all the words in a list.
Instructions
- 1
Print the names of the jumpers in alphabetical order, joined into one line with
", ".join():Anna, Eva, Lily, Max, Tom. Leave the line with the results as it is: the exercise also runs your program with other results. - 2
Below, print the three best jumpers from the longest jump, each on its own line with their result, for example
Eva: 435. Write your own key function for it.