Python enumerate, zip, reversed and sorted
What you will learn
enumerate: the position and the item togetherzip: walking two or more collections side by side,strict=True, and unzippingreversed: going backwardssorted: going in order, withkeyandreverse- That iterators can be used only once
These four tools solve most "I need the index", "I have two lists" and "I want it ordered" problems, so you rarely need range(len(...)) (lesson 6.2).
1. enumerate: position and item
enumerate hands you a pair: the position and the item. You unpack the pair into two names (lesson 2.1):
names = ["Rina", "Sam", "Lee"]
for i, name in enumerate(names):
print(i, name, end="; ")
print()
0 Rina; 1 Sam; 2 Lee;
By default counting starts at 0. Use start= for a different first number, such as 1 for a numbered list:
for i, name in enumerate(names, start=1):
print(f"{i}. {name}", end="; ")
print()
1. Rina; 2. Sam; 3. Lee;
It works on any collection, strings included. Over a dictionary it counts the keys:
print(list(enumerate("ab")))
print(list(enumerate({"k": 1, "j": 2})))
[(0, 'a'), (1, 'b')]
[(0, 'k'), (1, 'j')]
Quick check: what does `list(enumerate(["x", "y"], 5))` give?
[(5, 'x'), (6, 'y')]. The count starts at 5.
2. zip: two collections side by side
zip pairs up the items at the same position of two or more collections:
scores = [90, 75, 82]
for name, score in zip(names, scores):
print(name, score, end="; ")
print()
Rina 90; Sam 75; Lee 82;
With three or more collections, you get tuples of that length:
print(list(zip([1, 2], "ab", [True, False])))
[(1, 'a', True), (2, 'b', False)]
zip stops at the shortest
If the lengths differ, zip quietly stops at the shortest one, which can hide a mistake:
print(list(zip([1, 2, 3], "ab")))
[(1, 'a'), (2, 'b')]
The 3 was dropped without a warning. From Python 3.10, give strict=True to turn a length mismatch into an error:
list(zip([1, 2, 3], "ab", strict=True))
ValueError: zip() argument 2 is shorter than argument 1
If you want to keep the extras, itertools.zip_longest fills the gaps:
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], "ab")))
print(list(zip_longest([1, 2, 3], "ab", fillvalue="-")))
[(1, 'a'), (2, 'b'), (3, None)]
[(1, 'a'), (2, 'b'), (3, '-')]
Unzipping and dictionaries
zip(*pairs) does the reverse: it turns a list of pairs into separate collections. The star * spreads the list into separate arguments (chapter 11):
pairs = [(1, "a"), (2, "b"), (3, "c")]
nums, letters = zip(*pairs)
print(nums, letters)
(1, 2, 3) ('a', 'b', 'c')
And dict(zip(keys, values)) builds a dictionary from two lists:
print(dict(zip(names, scores)))
{'Rina': 90, 'Sam': 75, 'Lee': 82}
Using both together
Put the pair from zip in brackets when you also enumerate:
for i, (name, score) in enumerate(zip(names, scores), 1):
print(i, name, score, end="; ")
print()
1 Rina 90; 2 Sam 75; 3 Lee 82;
3. reversed: backwards
reversed goes through a sequence from the end to the start, without copying it or changing it:
for n in reversed(range(1, 4)):
print(n, end=" ")
print()
print(list(reversed([1, 2, 3])), list(reversed("abc")))
3 2 1
[3, 2, 1] ['c', 'b', 'a']
It works on lists, strings, tuples and ranges, but not on sets or generators, which have no order to reverse:
reversed({1, 2, 3})
TypeError: 'set' object is not reversible
To reverse the text of a string, slicing s[::-1] (lesson 4.2) or "".join(reversed(s)) both work. To reverse a list in place, use lst.reverse() (chapter 7).
4. sorted: in order
sorted returns a new list with the items in order. The original is unchanged:
lst = [3, 1, 2]
print(sorted(lst))
print(sorted(lst, reverse=True))
print(lst)
[1, 2, 3]
[3, 2, 1]
[3, 1, 2]
lst.sort() is the in-place twin: it changes the list and returns None (lesson 2.6), so never write lst = lst.sort().
sorted accepts any collection and always gives a list: sorted("hello") is ['e', 'h', 'l', 'l', 'o'], and sorted(d) sorts a dictionary's keys.
The key option
key= names a function that computes what to sort by for each item:
words = ["banana", "Apple", "cherry", "apple"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len))
print(sorted(words, key=lambda w: (len(w), w)))
['Apple', 'apple', 'banana', 'cherry']
['Apple', 'apple', 'banana', 'cherry']
['Apple', 'apple', 'banana', 'cherry']
['Apple', 'apple', 'banana', 'cherry']
- Plain
sortedputs capitals first (code order, lesson 4.1). key=str.lowerignores case.key=lensorts by length. When the keys are equal, the original order is kept (the sort is stable), soApplestays beforeapple.key=lambda w: (len(w), w)sorts by length, then alphabetically. Alambdais a tiny nameless function (lesson 11.7).
Sorting dictionaries and records
d = {"a": 3, "b": 1, "c": 2}
print(sorted(d.items()))
print(sorted(d.items(), key=lambda kv: kv[1]))
print(sorted(d, key=d.get, reverse=True))
people = [("Rina", 25), ("Sam", 22), ("Lee", 25)]
print(sorted(people, key=lambda p: (-p[1], p[0])))
[('a', 3), ('b', 1), ('c', 2)]
[('b', 1), ('c', 2), ('a', 3)]
['a', 'c', 'b']
[('Lee', 25), ('Rina', 25), ('Sam', 22)]
- Sorting
d.items()bykv[1]orders the pairs by value. sorted(d, key=d.get, reverse=True)lists the keys, biggest value first.- A minus sign reverses a number key, so
-p[1]sorts ages from largest to smallest, with namesA to Zfor ties.
Mixed types cannot be compared, so sorted([3, "a", 1]) raises TypeError: '<' not supported between instances of 'str' and 'int'.
5. Iterators can be used once
enumerate, zip and reversed give back iterators: they hand out their items one at a time and then they are empty:
e = enumerate(names)
print(list(e))
print(list(e))
r = reversed([1, 2, 3])
print(next(r), list(r), list(r))
[(0, 'Rina'), (1, 'Sam'), (2, 'Lee')]
[]
3 [2, 1] []
The second list(e) is empty because the first one used everything up. If you need the items twice, make a list first: pairs = list(zip(a, b)). Iterators are the subject of lesson 12.4.
Worked example: a leaderboard
Rank three players by score, highest first, and show the place number.
names = ["Rina", "Sam", "Lee"]
scores = [90, 75, 82]
ranking = sorted(zip(names, scores), key=lambda p: p[1], reverse=True)
for place, (name, score) in enumerate(ranking, start=1):
print(f"{place}. {name} - {score}")
1. Rina - 90
2. Lee - 82
3. Sam - 75
| Step | Tool | Result |
|---|---|---|
| pair names with scores | zip |
("Rina", 90), ("Sam", 75), ("Lee", 82) |
| order by score, biggest first | sorted(..., key=..., reverse=True) |
Rina, Lee, Sam |
| number the places from 1 | enumerate(..., start=1) |
1, 2, 3 |
The names and scores are made up.
Common mistakes
- Writing
range(len(x))and indexing whenenumerateis clearer. - Forgetting that
zipstops at the shortest. Usestrict=Truewhen lengths must match. - Writing
lst = lst.sort(), which storesNone. - Using an iterator twice. The second pass is empty; make a list.
- Sorting mixed types, such as numbers and text together.
- Expecting
sortedto change the original collection.
Key takeaways
enumerate(items, start=1)gives(position, item)pairs.zip(a, b)walks collections together and stops at the shortest;strict=True(Python 3.10+) checks the lengths;zip(*pairs)unzips.reversed(seq)goes backwards without copying; sets and generators cannot be reversed.sorted(items, key=..., reverse=...)returns a new sorted list; the sort is stable;list.sort()works in place and returnsNone.enumerate,zipandreversedgive one-use iterators: make a list to use the items again.
Practice
1. Print each fruit of ["fig", "kiwi"] with a number starting from 1.
Show answer
for n, fruit in enumerate(["fig", "kiwi"], start=1):
print(n, fruit)
2. What does list(zip("abc", [1, 2])) give?
Show answer
[('a', 1), ('b', 2)]. The c is dropped, because zip stops at the shortest.
3. Build the dictionary {"x": 1, "y": 2} from the lists ["x", "y"] and [1, 2].
Show answer
dict(zip(["x", "y"], [1, 2])).
4. Print the numbers from 5 down to 1 using reversed.
Show answer
for n in reversed(range(1, 6)):
print(n)
5. Sort ["bb", "a", "ccc"] from longest to shortest.
Show answer
sorted(["bb", "a", "ccc"], key=len, reverse=True) gives ['ccc', 'bb', 'a'].
6. Why does for x in e: give nothing the second time, when e = enumerate(items)?
Show answer
enumerate returns an iterator, which is used up after one pass. Create a new enumerate, or make a list with list(enumerate(items)).