Python Searching and Sorting Lists
What you will learn
- Searching:
in,index,count - Sorting in place with
sort()and into a new list withsorted() - The
keyandreverseoptions, and why sorting is stable - Sorting records by one or more fields
minandmaxwith a key- Fast searching in a sorted list with
bisect
1. Searching
Three tools answer three different questions:
| Question | Tool | Result |
|---|---|---|
| is it in the list? | x in lst |
True or False |
| where is it? | lst.index(x) |
the position of the first match, or ValueError |
| how many are there? | lst.count(x) |
a number (0 if none) |
nums = [30, 10, 20, 10]
print(20 in nums)
print(nums.index(10), nums.index(10, 2))
print(nums.count(10), nums.count(99))
True
1 3
2 0
nums.index(10)is1, the first10.- A second argument says where to start:
nums.index(10, 2)starts at index2and finds the10at index3. - If the value is missing,
indexraises an error:
nums.index(99)
ValueError: 99 is not in list
Check with in first, or use a conditional expression (lesson 5.4):
print(nums.index(10) if 10 in nums else -1)
1
All these tools look at the items one by one from the start, so on a huge list they are slow. For fast lookups, use a set or a dictionary (chapters 9 and 10), or a sorted list with bisect (section 6 below).
index and count also exist on strings and tuples.
Quick check: what does `[5, 7, 5].index(5)` give?
0. It gives the position of the first match.
2. Sorting: sort() and sorted()
There are two ways to sort. Choose by whether you want to change the list or keep the original:
lst.sort() |
sorted(lst) |
|
|---|---|---|
| changes the original | yes, in place | no |
| returns | None |
a new list |
| works on | lists only | any collection |
nums = [30, 10, 20, 10]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
print(sorted(nums), nums)
[10, 10, 20, 30]
[30, 20, 10, 10]
[10, 10, 20, 30] [30, 20, 10, 10]
The third line shows sorted(nums) as a new ascending list, while nums itself stays in descending order.
Remember that sort() returns None (lessons 2.6 and 7.2): nums = nums.sort() is a bug. Use nums.sort() alone, or nums = sorted(nums).
Numbers sort from small to large. Text sorts by character code, so capitals come before lower-case letters, and numbers written as text sort as text (lessons 4.1 and 6.6):
words = ["banana", "Cherry", "apple", "date"]
words.sort()
print(words)
print(sorted(["10", "9", "100"]))
print(sorted(["10", "9", "100"], key=int))
['Cherry', 'apple', 'banana', 'date']
['10', '100', '9']
['9', '10', '100']
Mixed types cannot be compared: [3, "a"].sort() raises TypeError: '<' not supported between instances of 'str' and 'int'.
3. The key option
key= is a function that is called on each item to decide what to sort by:
words = ["banana", "Cherry", "apple", "date"]
words.sort(key=str.lower)
print(words)
words.sort(key=len)
print(words)
words.sort(key=len, reverse=True)
print(words)
['apple', 'banana', 'Cherry', 'date']
['date', 'apple', 'banana', 'Cherry']
['banana', 'Cherry', 'apple', 'date']
key=str.lowerignores case.key=lensorts by length.reverse=Trueflips the order.
Sorting is stable
When two items have equal keys, they keep the order they had before. In the second line, banana and Cherry both have length 6, and banana stays first because it came first. Even with reverse=True they stay in the original order, as the third line shows. Stability lets you sort in two steps: sort by the less important field first, then by the more important one.
Records
For lists of tuples or dictionaries, the key picks the field. A tuple as a key sorts by several fields in turn:
records = [("b", 2), ("a", 2), ("c", 1)]
print(sorted(records, key=lambda r: r[1]))
print(sorted(records, key=lambda r: (r[1], r[0])))
print(sorted(records, key=lambda r: (-r[1], r[0])))
people = [{"name": "Rina", "age": 25}, {"name": "Sam", "age": 22}]
print(sorted(people, key=lambda p: p["age"]))
[('c', 1), ('b', 2), ('a', 2)]
[('c', 1), ('a', 2), ('b', 2)]
[('a', 2), ('b', 2), ('c', 1)]
[{'name': 'Sam', 'age': 22}, {'name': 'Rina', 'age': 25}]
r[1]sorts by the number only, so the tie betweenbandakeeps the original order.(r[1], r[0])sorts by number, then by letter.(-r[1], r[0])sorts the number largest first, then by letter: the minus sign reverses a number key.
A lambda is a tiny nameless function (lesson 11.7). Lists of lists and tuples also sort without a key, item by item from the left: sorted([(2, "b"), (1, "z"), (2, "a")]) is [(1, 'z'), (2, 'a'), (2, 'b')].
4. min and max with a key
min and max also take a key, and give back the item whose key is smallest or largest:
print(max(["apple", "fig"], key=len), min(["apple", "fig"], key=len))
print(max(people, key=lambda p: p["age"])["name"])
apple fig
Rina
If the largest key appears in several items, you get the first one.
5. The median, the top three
Sorting makes many statistics easy. The median is the middle value of the sorted data, or the average of the two middle values when there is an even count:
data = [5, 3, 8, 1]
data.sort()
mid = len(data) // 2
if len(data) % 2 == 0:
median = (data[mid - 1] + data[mid]) / 2
else:
median = data[mid]
print(data, median)
[1, 3, 5, 8] 4.0
The top three values are the last three of the sorted list: sorted(data)[-3:], or sorted(data, reverse=True)[:3]. For huge lists, heapq.nlargest is faster (lesson 9.6 shows it; the heapq module is part of the standard library).
Finding duplicates
nums = [4, 2, 4, 1]
print([v for v in set(nums) if nums.count(v) > 1])
print([i for i, v in enumerate(nums) if v == 4])
[4]
[0, 2]
The first line lists the repeated values; the second finds every position of a value. (count inside a loop searches the whole list each time, so this is slow for big lists; lesson 6.5 shows the faster dictionary method.)
6. Fast searching in a sorted list: bisect
If a list is already sorted, the bisect module finds a position by repeatedly halving the range (the idea of lesson 6.7), which is much faster than looking at every item:
import bisect
s = [1, 3, 5, 7]
print(bisect.bisect_left(s, 5), bisect.bisect_left(s, 4), bisect.bisect_right(s, 5))
bisect.insort(s, 4)
print(s)
2 2 3
[1, 3, 4, 5, 7]
bisect_left(s, x)is the position wherexis or would go, before any equal items.bisect_right(s, x)is the position after any equal items.insort(s, x)insertsxand keeps the list sorted.
The list must really be sorted, or the answers are meaningless.
Worked example: a leaderboard with ties
Rank players by score (highest first). When scores tie, order the names A to Z.
players = [("Sam", 82), ("Lee", 90), ("Mia", 82), ("Rina", 90)]
ranked = sorted(players, key=lambda p: (-p[1], p[0]))
for place, (name, score) in enumerate(ranked, start=1):
print(f"{place}. {name} {score}")
print("best:", max(players, key=lambda p: p[1])[0])
1. Lee 90
2. Rina 90
3. Mia 82
4. Sam 82
best: Lee
| Step | Why |
|---|---|
key (-p[1], p[0]) |
score from high to low (minus sign), then name from A to Z |
enumerate(..., start=1) |
numbers the places |
max(..., key=...) |
the first player with the top score, which is Lee |
The names and scores are made up.
Common mistakes
- Writing
nums = nums.sort(). It storesNone. - Using
indexon a value that may be missing without a check. - Sorting numbers stored as text. Use
key=int, or convert first. - Sorting mixed types such as numbers and text.
- Using
bisecton a list that is not sorted. - Forgetting that
sort()changes the original when you still need the old order.
Key takeaways
in,indexandcountsearch from the start;indexraisesValueErrorif the item is missing.lst.sort()sorts in place and returnsNone;sorted(x)returns a new list and works on anything.key=chooses what to sort by,reverse=Trueflips the order, and the sort is stable.- A tuple key sorts by several fields; a minus sign reverses a number field.
minandmaxaccept a key;bisectsearches and inserts into a sorted list quickly.
Practice
1. What do [4, 7, 4].count(4) and [4, 7, 4].index(7) give?
Show answer
2 and 1.
2. Sort ["pear", "Fig", "apple"] ignoring case.
Show answer
sorted(["pear", "Fig", "apple"], key=str.lower) gives ['apple', 'Fig', 'pear'].
3. Sort ["10", "9", "100"] as numbers.
Show answer
sorted(["10", "9", "100"], key=int) gives ['9', '10', '100'].
4. Which is the longest word in ["hi", "hello", "hey"]? Write it with max.
Show answer
max(["hi", "hello", "hey"], key=len) gives "hello".
5. Sort [("a", 3), ("b", 1), ("c", 3)] by number, largest first, then by letter.
Show answer
sorted(items, key=lambda r: (-r[1], r[0])) gives [('a', 3), ('c', 3), ('b', 1)].
6. What is the median of [7, 1, 5]?
Show answer
Sorted it is [1, 5, 7], so the middle value is 5.