
Python practice
Python sorting practice questions
8 problems, ordered from easiest. They run in your browser, and 4 are free.
Start with Second largest order totalOn this page12 sections
The idea in a minute
You almost never write a sort. You call sorted and tell it what to sort by. That second part, the key, is where the thinking is.
Below: sorted versus sort, keys and lambdas, ties and stability, sorting by two things at once, and how a sorted list turns hard questions into easy ones.
You almost never write a sort yourself
In an interview you may be asked to write bubble sort. In real work you call sorted(). Your job is to tell it what to sort by. That "what by" is the key, and it is the thing worth learning.
nums = [4, 1, 3, 9, 2]
print(sorted(nums))
print(sorted(nums, reverse=True))
print(sorted(["pune", "Delhi", "goa"]))
print(nums)[1, 2, 3, 4, 9] [9, 4, 3, 2, 1] ['Delhi', 'goa', 'pune'] [4, 1, 3, 9, 2]
Two things to notice. Capital letters sort before lowercase ones (Delhi came before goa and pune because D comes before g in the character table). And nums itself is unchanged: sorted returns a new list.
sorted or .sort()?
nums = [4, 1, 3]
result = nums.sort()
print(result)
print(nums)None [1, 3, 4]
A classic bug: writing nums = nums.sort() and ending up with None. sort() works in place and returns nothing. Use sorted(nums) when you want a new list, and nums.sort() when you want to change the existing one.
The key: what should I compare?
The key is a function. Python calls it on each item once, and sorts the items by what the function returns. Sort words by length? The key is len. Sort rows by the second column? The key picks the second column.
words = ["banana", "fig", "apple", "kiwi"]
print(sorted(words, key=len))
rows = [("Asha", 92), ("Ravi", 85), ("Dev", 70)]
print(sorted(rows, key=lambda r: r[1]))['fig', 'kiwi', 'apple', 'banana']
[('Dev', 70), ('Ravi', 85), ('Asha', 92)]lambda r: r[1] is a tiny unnamed function that takes a row and returns its second item. You could write it as a normal def, it is only shorter.
Ties, and breaking them
Two people scored 92. Which one comes first? Python's sort is stable, which means items with equal keys keep the order they had before. That is a promise you can rely on.
rows = [("Asha", 92), ("Ravi", 85), ("Meera", 92), ("Dev", 70)]
print(sorted(rows, key=lambda r: r[1], reverse=True))[('Asha', 92), ('Meera', 92), ('Ravi', 85), ('Dev', 70)]When you want a rule instead of leaving it to the original order, make the key a tuple. Python compares tuples left to right: first the first item, and only if those tie, the second.
How the key decides
1rows = [("Asha", 92), ("Ravi", 85), ("Meera", 92), ("Dev", 70)]2print(sorted(rows, key=lambda r: (-r[1], r[0])))
rows = [("Asha", 92), ("Ravi", 85), ("Meera", 92), ("Dev", 70)]
print(sorted(rows, key=lambda r: (-r[1], r[0])))[('Asha', 92), ('Meera', 92), ('Ravi', 85), ('Dev', 70)]The minus sign in -r[1] is the trick for mixed directions. Sorting by -score ascending puts the highest score first, while the name stays ascending. For text you cannot negate, sort twice (the stable property makes that work) or use a different key.
Sorting dictionaries
stock = {"pen": 12, "book": 3, "bag": 0, "ink": 12}
by_qty = sorted(stock.items(), key=lambda kv: (-kv[1], kv[0]))
print(by_qty)
print(dict(by_qty))
print(sorted(stock))[('ink', 12), ('pen', 12), ('book', 3), ('bag', 0)]
{'ink': 12, 'pen': 12, 'book': 3, 'bag': 0}
['bag', 'book', 'ink', 'pen']stock.items() gives (key, value) pairs, and those are what you sort. sorted(stock) on its own sorts just the keys.
Why sorting solves other problems
Once things are in order, a lot of questions stop being hard. Equal items sit side by side. The smallest and largest are at the ends. You can binary search. You can use two pointers.
nums = [5, 3, 5, 1, 3, 3]
s = sorted(nums)
dups = sorted({s[i] for i in range(1, len(s)) if s[i] == s[i - 1]})
print(s)
print(dups)[1, 3, 3, 3, 5, 5] [3, 5]
meetings = [(9, 11), (10, 12), (14, 15), (8, 9)]
meetings.sort()
merged = [meetings[0]]
for start, end in meetings[1:]:
if start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
print(merged)[(8, 12), (14, 15)]
Sorted by start time, a meeting can only overlap with the one just before it. That one fact turns a messy comparison of every pair into a single pass.
Sorting strings and mixed data
names = ["asha", "Ravi", "meera", "Dev"]
print(sorted(names))
print(sorted(names, key=str.lower))
nums_as_text = ["10", "9", "100"]
print(sorted(nums_as_text))
print(sorted(nums_as_text, key=int))['Dev', 'Ravi', 'asha', 'meera'] ['asha', 'Dev', 'meera', 'Ravi'] ['10', '100', '9'] ['9', '10', '100']
Text sorts character by character, so '100' comes before '9' because '1' is less than '9'. If the values are really numbers, sort with key=int.
Cost
Sorting takes about n log n steps. For a million items that is about twenty million, which is nothing. It is only worth avoiding when you can answer the question without it in a single pass (like finding the maximum).
Questions people ask
What is the difference between sorted and sort?
sorted(x) returns a new sorted list and works on anything you can loop over. x.sort() changes a list in place and returns None.
What does stable mean?
Items that compare equal stay in their original relative order. It is why sorting by name and then by score gives you scores in order, with names in order inside each score.
Can I sort a list with mixed numbers and text?
Not directly, Python raises a TypeError. Convert them, or give a key that returns a comparable value.
Keep this checklist handy
- sorted returns a new list and list.sort changes the list in place.
- Python sorting is stable: items with equal keys keep their original order.
- To sort in descending order on one field only, negate a number in the key instead of using reverse for everything.
Now try it yourself
8 sorting problems. They run right here in your browser, and you can start anywhere.
Warm up
One idea at a time. Do these in order.
Getting comfortable
Two ideas together, or a trap to spot.
Stretch
Interview style. Take your time.
Want a guided order across every topic? Open the practice sheets or the Python hub.
More Python topics
Python
Strings
Slice, count and clean text
15 problemsPractice
Python
Dictionaries
Group and count by key
16 problemsPractice
Python
Hashing
Trade memory for a single pass
13 problemsPractice
Python
Arrays
Loop, accumulate, reverse
15 problemsPractice
Python
Two pointers
Walk in from both ends
5 problemsPractice
Python
Sliding window
Slide once instead of re-adding
11 problemsPractice
Python
Sorting
Order by a key, then reason about neighbours
You are here
Python
Stacks
Last in, first out
7 problemsPractice
Python
Recursion
A function that calls itself
8 problemsPractice