sorted()
sorted() returns a new list with the items of any iterable in order, without changing the original.
Used in 51 lessons of the course, from 00.01.
sorted(iterable) walks through whatever you give it (list, tuple, set, dict, generator) and returns a new list in ascending order. The original is untouched.
That is the difference from list.sort(): that method sorts the list in place and returns None. sorted() works on any iterable, which makes it the more flexible choice.
You can pass reverse=True for descending order and key= to choose what to sort by.
In the course, lesson 00.01 writes return sorted(t for t, (d, _) in GLOSSARY.items() if ...). It hands a generator expression to sorted() and gets back a list of terms in alphabetical order. The result always comes out in the same order, even if the dict changes.
Reach for it when: you need items in order and want to keep the original, or when you have an iterable that is not a list (a set, a dict, a generator).
Examples
Common mistake
nums = [3, 1, 2] sorted(nums) print(nums)
Why: `sorted()` does not change the list; it returns a new one, and here you threw it away.
How to write it: Keep the result: nums = sorted(nums), or use nums.sort() to sort in place.
Common mistake
print(sorted([3, "a", 1]))
Why: Python cannot compare a number with a string, so it cannot sort them together.
How to write it: Make everything the same type first, for example with key=str.
