From the Largest
sorted() and .sort() both sort from the smallest to the largest, and texts from A to Z. For the opposite order, add reverse=True in the parentheses:
scores = [72, 45, 90, 38, 64]
print(sorted(scores, reverse=True))
names = ["Tom", "Anna", "Max", "Eva"]
names.sort(reverse=True)
print(names)[90, 72, 64, 45, 38]
['Tom', 'Max', 'Eva', 'Anna']reverse=True is an argument written with the name of its parameter, like start=1 in enumerate(). Both sorted() and .sort() have a parameter reverse with the default value False, and with True they sort the other way round. The name is needed: sorted(scores, True) ends with TypeError: sorted expected 1 argument, got 2. And True is written with a capital T, because reverse=true ends with NameError: name 'true' is not defined. Did you mean: 'True'?
Sorting from the largest is the first step of every leaderboard. The second step is to take only the best few, and you already know how to take the first three elements of a list: the slice [:3]. Write it right after the call:
scores = [72, 45, 90, 38, 64]
top_three = sorted(scores, reverse=True)[:3]
print(top_three)[90, 72, 64]Read it from left to right: sorted() returns a new list from the largest, and [:3] takes its first three elements. If the list has fewer than three elements, the slice gives you all of them, without an error.
The lowest values work the same way, without reverse: sorted(times)[:3] are the three shortest times, for example of the three fastest runners in a race.
Instructions
- 1
Print
pointssorted from the highest:[31, 27, 22, 18, 14, 9]. Leave the line with the points as it is: the exercise also runs your program with other points. - 2
Below, print the three best results with the label
Top 3:. Usereverse=Trueand a slice. The output should beTop 3: [31, 27, 22].