← All lessons

sort and sorted

Sign in · Sign up

Lesson 5.5

Two ways to sort a list — and the difference between them matters:

scores = [5, 3, 4, 2]

scores.sort()                      # changes the list itself
print(scores)                      # [2, 3, 4, 5]

new_scores = sorted(scores, reverse=True)   # returns a new list
print(new_scores)                  # [5, 4, 3, 2]

sort() returns None — that's why scores = scores.sort() leaves None in the variable. sorted() returns a new list and leaves the original alone.

The list of numbers values is set by the check. Print, in order:

  1. ascending — with sorted, without changing the original list;
  2. descending — with reverse=True;
  3. the original list once more, so you can see it didn't change.
Hint

sorted(list) returns a new list and does not change the original.

The direction is set by reverse=True in the second sorted. The third print is the original list itself: it must stay as it was.