0Pricing
Competitive Programming Academy · Lesson

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

  1. sorted() and the key Function
  2. Sort by Multiple Fields
  3. Custom Order with functools.cmp_to_key
  4. Why Sorting First Unlocks Solutions
← Back to Competitive Programming Academy