0Pricing
Coding Interview Prep · Lesson

sorted() and the key Function

Sort numbers, strings, and tuples.

sorted() and the key Function is a free Coding Interview Prep lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Coding Interview Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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]

list.sort() Sorts in Place

When you do not need the original order, list.sort() sorts in place and returns None. It saves memory on big arrays.

nums = [3, 1, 2]
nums.sort()
print(nums)   # [1, 2, 3]

Default Order Is Ascending

By default Python sorts from smallest to largest. Numbers go low to high and strings go in dictionary order, character by character.

print(sorted(["pear", "apple", "kiwi"]))
# ['apple', 'kiwi', 'pear']

Flip It with reverse

Pass reverse=True to sort from largest to smallest. Perfect when a greedy step needs the biggest items first.

print(sorted([3, 1, 2], reverse=True))
# [3, 2, 1]

Meet the key Function

The key argument tells sort how to rank each item. Python calls key on every element and orders by those returned values.

words = ["bb", "a", "ccc"]
print(sorted(words, key=len))
# ['a', 'bb', 'ccc']

key with a lambda

A tiny lambda lets you sort by any expression inline. Here we order numbers by how far they sit from zero.

vals = [-5, 2, -1, 3]
print(sorted(vals, key=lambda x: abs(x)))
# [-1, 2, 3, -5]

Sort Objects by a Field

With tuples or records, point key at the field that matters. The rest of the item rides along for free.

people = [("Ann", 30), ("Bob", 25)]
print(sorted(people, key=lambda p: p[1]))
# [('Bob', 25), ('Ann', 30)]

Sort Is Stable

Python sorting is stable: equal keys keep their original relative order. This lets you layer sorts to break ties safely.

key Beats Comparing by Hand

A key is computed once per element, so it stays fast on large inputs. Reach for it instead of swapping items yourself.

Sorting Costs O(n log n)

Python sorts in O(n log n) time. For n up to a few hundred thousand it comfortably fits inside a one-second limit.

Quick Check

You need the list ordered but must keep the original intact.

Recap

You can order data with sorted() or sort in place, flip with reverse, and rank anything using a key. Stable sorting keeps ties tidy. 🎉

Frequently asked questions

Is the “sorted() and the key Function” lesson free?

Yes — the full text of “sorted() and the key Function” is free to read here on the web, and the Coding Interview Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Coding Interview Prep course, upgrade to CoddyKit PRO.

What will I learn in “sorted() and the key Function”?

Sort numbers, strings, and tuples. You practise Coding Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Coding Interview Prep?

No prior experience is required. Coding Interview Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “sorted() and the key Function” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Coding Interview Prep lesson?

Yes. Every Coding Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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 Coding Interview Prep