Sorting with sorted() & key

Published by Brayan K

Sorting in Python means ordering items with sorted() (which returns a new list) or list.sort() (which sorts in place), optionally guided by a key function that decides what to sort by.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose whether the original list should change

Use sorted() when you need a new ordered list and must preserve the original order. Use a list’s sort() method when changing that list is intentional. The method returns None, so assigning its result does not give you the sorted list.

scores = [7, 2, 5]
ordered = sorted(scores)
print("original:", scores)
print("ordered:", ordered)

alias = scores
result = scores.sort()
print("result:", result)
print("alias:", alias)

# ✅ Expected output:
# original: [7, 2, 5]
# ordered: [2, 5, 7]
# result: None
# alias: [2, 5, 7]

The alias sees the changed list because both names refer to that same object. sorted() accepts any iterable, whereas sort() is a list method. Neither operation recursively copies the objects inside a list; mutation and aliasing belong to Lists in Python.

Treat the returned None as a deliberate signal, not an empty sorted result. None & NoneType explains why absence and empty data need different tests.

A key chooses what to compare, not what to return

A key function receives one original item and returns a comparison value. The ordered result still contains the original items. This makes a key useful when the stored representation is not the ordering you want: numeric strings should often be ordered by their numeric value rather than their first character.

codes = ["10", "2", "1"]
print(sorted(codes))
print(sorted(codes, key=int))

words = ["pear", "fig", "apple"]
print(sorted(words, key=len))

# ✅ Expected output:
# ['1', '10', '2']
# ['1', '2', '10']
# ['fig', 'pear', 'apple']

Pass a callable such as len, not the result of calling len() immediately. Lambda Functions teaches that distinction and one-expression functions; this lesson uses keys to establish a complete ordering.

calls = []
def by_length(word):
    calls.append(word)
    return len(word)

words = ["pear", "fig", "apple"]
print(sorted(words, key=by_length))
print("key inputs:", calls)
print("calls:", len(calls))

# ✅ Expected output:
# ['fig', 'pear', 'apple']
# key inputs: ['pear', 'fig', 'apple']
# calls: 3

This count describes key extraction for one sort, not the number of comparisons. Avoid changing the input collection from the key function. A key should describe the item; it should not rearrange the data being ordered.

Sort dictionary keys or key-value pairs deliberately

Iterating a dictionary supplies keys. Therefore sorted(scores) orders names, not scores. Use the mapping's lookup method as the key function when you want names ordered by their values, or sort items() when the result should retain both parts.

from operator import itemgetter

scores = {"Mira": 8, "Ada": 10, "Noor": 8}
print("names:", sorted(scores))
print("by score:", sorted(scores, key=scores.get))
pairs = sorted(scores.items(), key=itemgetter(1))
print("pairs:", pairs)
print("original:", list(scores.items()))

# ✅ Expected output:
# names: ['Ada', 'Mira', 'Noor']
# by score: ['Mira', 'Noor', 'Ada']
# pairs: [('Mira', 8), ('Noor', 8), ('Ada', 10)]
# original: [('Mira', 8), ('Ada', 10), ('Noor', 8)]

itemgetter(1) makes a callable that retrieves item[1], the value from each pair. It does not call the dictionary or modify it. Equal scores keep their insertion order here because sorting is stable. A list of sorted pairs is often enough; dict(pairs) builds a new dictionary whose iteration follows that order. Dictionaries in Python owns mapping lookup and insertion order.

from operator import itemgetter

people = [
    {"name": "Mira", "age": 24},
    {"name": "Noor", "age": 20},
    {"name": "Ada", "age": 24},
]
print([row["name"] for row in sorted(people, key=itemgetter("age"))])
print([row["name"] for row in sorted(people, key=itemgetter("age", "name"))])

# ✅ Expected output:
# ['Noor', 'Mira', 'Ada']
# ['Noor', 'Ada', 'Mira']

With one field, itemgetter returns that value. With several, it returns a tuple, so age is compared first and name breaks ties. This is the field-extraction helper introduced in Higher-Order Functions & Function Factories (Python). It requires every requested key; it does not invent a default for an incomplete record:

from operator import itemgetter

people = [{"name": "Ada", "age": 24}, {"name": "Mira"}]
print(sorted(people, key=itemgetter("age")))

# ✅ Expected error:
# KeyError: 'age'

Validate required fields before sorting, or write an explicit key for your missing-value policy as below. Use a lambda when a key needs a calculation or a transformation rather than just field extraction.

Make every comparison meaningful

Python does not invent an ordering between every pair of object types. A mix of numbers and numeric text may look comparable to a person, but ordinary sorting cannot decide that policy for you. Convert the data explicitly or use a key whose results have compatible types.

print(sorted([3, "2", 1]))

# ✅ Expected error:
# TypeError: '<' not supported between instances of 'str' and 'int'
values = [3, "2", 1]
numbers = [int(value) for value in values]
print(sorted(numbers))

# ✅ Expected output:
# [1, 2, 3]

A missing value also needs a policy. Putting None last is different from replacing it with zero, which would lose the distinction between a real zero and an absent reading.

print(sorted([9, None, 0]))

# ✅ Expected error:
# TypeError: '<' not supported between instances of 'NoneType' and 'int'
readings = [9, None, 0, 3, None]
print(sorted(readings, key=lambda value: (value is None, value)))

# ✅ Expected output:
# [0, 3, 9, None, None]

Tuple keys compare the first position before moving to later positions. Here the boolean marker separates present readings from absent ones, so a number is never compared with None. Within the present group, the second field orders the numbers. Choose this policy deliberately; dropping missing readings would answer a different question.

Keep tied records in a predictable order

Sorting is stable: records with equal keys keep their input order. That remains true with reverse=True. Reversing an already sorted list reverses tied groups as well, so it is not equivalent when tie order matters.

records = [("Mira", 2), ("Noor", 1), ("Ada", 2)]
ascending = sorted(records, key=lambda row: row[1])
descending = sorted(records, key=lambda row: row[1], reverse=True)
print("ascending:", [name for name, score in ascending])
print("descending:", [name for name, score in descending])
print("reversed:", [name for name, score in ascending[::-1]])

# ✅ Expected output:
# ascending: ['Noor', 'Mira', 'Ada']
# descending: ['Mira', 'Ada', 'Noor']
# reversed: ['Ada', 'Mira', 'Noor']

Stability preserves the order you supplied; it does not create a meaningful tie-breaker for unordered input. If the product needs a name or identifier tie-breaker, include it in the key. Slice direction itself is covered by Slicing Lists & Strings.

Specify each direction in a multi-field ranking

A tuple key can express a ranking rule in one place. For numeric points descending and names ascending, negate the points but leave the name key in its ordinary direction. Setting reverse=True on the whole tuple would reverse both fields.

players = [("zoe", 8), ("Ada", 8), ("Mira", 10), ("ada", 8)]
ranked = sorted(players, key=lambda row: (-row[1], row[0].casefold()))
print(ranked)
print("input:", players)

# ✅ Expected output:
# [('Mira', 10), ('Ada', 8), ('ada', 8), ('zoe', 8)]
# input: [('zoe', 8), ('Ada', 8), ('Mira', 10), ('ada', 8)]

casefold() provides a case-insensitive text key, not a locale-specific dictionary order. Ada and ada have equal keys here, so their original relative order survives. Add another field when your rules require a further distinction. For non-numeric descending fields, stable successive sorts are another option: sort the secondary field first, then the primary field.

players = [("zoe", 8), ("Ada", 8), ("Mira", 10)]
by_name = sorted(players, key=lambda row: row[0].casefold())
ranked = sorted(by_name, key=lambda row: row[1], reverse=True)
print(ranked)

# ✅ Expected output:
# [('Mira', 10), ('Ada', 8), ('zoe', 8)]

Build the key for a delivery queue

Each delivery is a (name, priority) pair. Larger priorities should come first; equal priorities should use case-insensitive ascending names. Fill the two parts of the tuple key and leave the input list unchanged.

deliveries = [("Zed", 2), ("ada", 2), ("Mira", 4)]
ranked = sorted(deliveries, key=lambda row: (___, ___))
print(ranked)
print(deliveries)

# 👉 replace ___ with -row[1]
# 👉 replace ___ with row[0].casefold()

# ✅ Expected output:
# [('Mira', 4), ('ada', 2), ('Zed', 2)]
# [('Zed', 2), ('ada', 2), ('Mira', 4)]

Choose a leaderboard without losing valid zeroes

Build a leaderboard from the four records below. Exclude only absent scores; zero is valid. Rank the remaining records by points descending, then name ascending without case distinctions, and take the first two. Print those two records and the untouched original list. Make the filtering, ordering and slicing separate steps so their order is visible.

results = [("Zoe", 0), ("Ada", 9), ("Mira", None), ("Ben", 9)]
available = [row for row in results if row[1] is not None]
ranked = sorted(available, key=lambda row: (-row[1], row[0].casefold()))
leaders = ranked[:2]
print(leaders)
print(results)

# ✅ Expected output:
# [('Ada', 9), ('Ben', 9)]
# [('Zoe', 0), ('Ada', 9), ('Mira', None), ('Ben', 9)]

Practice quiz

What does this program print? values = [3, 1, 2] result = values.sort() print(result) print(values)

  • [1, 2, 3] [3, 1, 2]
  • None [1, 2, 3]
  • [1, 2, 3] [1, 2, 3]
  • None [3, 1, 2]

Answer: None [1, 2, 3]. sort mutates the list and returns None.

What does this program print? from operator import itemgetter scores = {"B": 2, "A": 1, "C": 2} print(sorted(scores.items(), key=itemgetter(1)))

  • ['A', 'B', 'C']
  • [('B', 2), ('C', 2), ('A', 1)]
  • [('A', 1), ('C', 2), ('B', 2)]
  • [('A', 1), ('B', 2), ('C', 2)]

Answer: [('A', 1), ('B', 2), ('C', 2)]. items supplies pairs, itemgetter(1) compares their values, and the tied B/C pair retains insertion order.

What does this program print? print(sorted(["12", "3", "1"], key=int))

  • ['1', '3', '12']
  • [1, 3, 12]
  • ['1', '12', '3']
  • TypeError

Answer: ['1', '3', '12']. The numeric keys change ordering, not the original string values in the result.

What does this program print? rows = [("A", 2), ("B", 2), ("C", 1)] print(sorted(rows, key=lambda row: row[1], reverse=True))

  • [('B', 2), ('A', 2), ('C', 1)]
  • [('C', 1), ('A', 2), ('B', 2)]
  • [('A', 2), ('B', 2), ('C', 1)]
  • [2, 2, 1]

Answer: [('A', 2), ('B', 2), ('C', 1)]. Descending sorting still preserves the input order of equal keys.

What does this program print? rows = [("Zed", 4), ("Ada", 4), ("Mira", 6)] print(sorted(rows, key=lambda row: (-row[1], row[0])))

  • [('Ada', 4), ('Zed', 4), ('Mira', 6)]
  • [('Mira', 6), ('Ada', 4), ('Zed', 4)]
  • [('Mira', 6), ('Zed', 4), ('Ada', 4)]
  • [6, 4, 4]

Answer: [('Mira', 6), ('Ada', 4), ('Zed', 4)]. Negating the numeric field reverses only that part of the ranking.

What does this program print? print(sorted([None, 0, 2], key=lambda n: (n is None, n)))

  • [None, 0, 2]
  • [0, None, 2]
  • TypeError
  • [0, 2, None]

Answer: [0, 2, None]. The marker groups present values first, preserving zero as a real reading.

What does this program print? rows = [("b", 1), ("a", 1)] print(sorted(rows, key=lambda row: row[1])[::-1])

  • [('a', 1), ('b', 1)]
  • [('b', 1), ('a', 1)]
  • [1, 1]
  • None

Answer: [('a', 1), ('b', 1)]. Reversing the sorted list reverses the tied pair, unlike reverse=True on the sort.

When equal keys must be ordered by arrival time, what makes a stable sort useful?

  • It guesses the arrival time from each object
  • It always sorts names alphabetically
  • It preserves an input order that already records arrival
  • It makes every key unique

Answer: It preserves an input order that already records arrival. Stability retains the order of tied records supplied by the caller; it cannot recover an order absent from the input.

Continue this course

Related lessons