Python Intermediate: Objects, Errors and Files
Comprehensions and Iteration Tools
In this lesson you will
- Write list, dictionary and set comprehensions
- Loop with enumerate and zip
- Sort with a key function and test collections with any and all
Introduction
A very common job is: take a collection, change or filter each item, and collect the results. With a loop it takes several lines. Python has a compact form called a comprehension that does it in one, and once you are used to it, it is easier to read.
From loop to comprehension
First the long way:
Now as a list comprehension. Read it as "n squared, for each n in numbers":
The pattern is [expression for item in collection].
Adding a filter
Add if at the end to keep only some items.
If you want to change values rather than drop items, use a conditional expression a if condition else b before the for:
Quick quiz
What does [n * 2 for n in [1, 2, 3]] give?
Dictionary and set comprehensions
The same idea works with curly brackets.
Nested loops in a comprehension
Keep comprehensions short. If you need more than two for parts or a complicated condition, a normal loop is easier to read.
enumerate: index and value
Instead of counting yourself, let enumerate give you both.
zip: loop over two lists together
zip stops at the shortest list.
Sorting with a key
sorted accepts a key function that says what to sort by.
lambda p: p[1] is a tiny unnamed function that returns the second item of each pair.
any, all, sum, min and max
Quick quiz
What does zip(['a', 'b'], [1, 2]) pair up?
Try it yourself
Given a list of words, build a dictionary that maps each word longer than 3 letters to its length, using one comprehension. Then print the words sorted by length, longest first.
Summary
[expr for x in items if cond]builds a list. Curly brackets make dictionary and set comprehensions.enumerategives index and value, andziploops over lists side by side.sorted(items, key=function)sorts by any rule.anyandalltest whole collections.- Keep comprehensions short and readable. Use a normal loop for complicated logic.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading