sorted() and the key Function
Sort numbers, strings, and tuples.
Sorting Wins Contests
So many contest problems get easy once the data is in order. Your first tool is sorted(), which returns a new ordered list. 🏆
sorted() Returns a Copy
Calling sorted(nums) leaves the original list untouched and hands you a fresh sorted list. Great when you still need the input later.
nums = [3, 1, 2]
print(sorted(nums)) # [1, 2, 3]
print(nums) # [3, 1, 2]All lessons in this course
- sorted() and the key Function
- Sort by Multiple Fields
- Custom Order with functools.cmp_to_key
- Why Sorting First Unlocks Solutions