Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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. 1

    Print points sorted 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. 2

    Below, print the three best results with the label Top 3:. Use reverse=True and a slice. The output should be Top 3: [31, 27, 22].

Back

4/9

  1. 1. Sorting with sorted()
  2. 2. The .sort() Method
  3. 3. Quiz: sort() or sorted()?
  4. 4. From the Largest
  5. 5. Sorting by Another Rule
  6. 6. Your Own Key
  7. 7. Quiz: Sorting
  8. 8. min() and max() with key
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.