Lessons · Python · sorted() gives a new list
A sorted copy
sorted(xs) returns a new list in order and leaves xs alone. xs.sort() sorts in place and returns None.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Leaderboards, alphabetical menus, oldest first: ordering is the last step of most reports, and whether the original survives decides whether the rest of the program still works.
How to think about it
Want to keep the original? sorted(). Happy to change it and done with the old order? .sort(). Never assign the result of .sort().
Worked example
xs = [3, 1, 2]Out of order.
print(sorted(xs))[1, 2, 3].
print(xs)[3, 1, 2]: untouched.
xs.sort()In place.
print(xs)[1, 2, 3]: now changed.
print(sorted("bca"))['a', 'b', 'c']: sorted takes any sequence and always returns a list.Your turn
The scores from highest to lowest, original untouched.
top = (scores, reverse=True)
Solve one with the tests running
The trap
xs = xs.sort() leaves xs as None. sort returns nothing on purpose, so the mistake shows up as a crash on the next line, not as a wrong order.