⚡ Comprehensions & Iteration, lesson 1 of 5
List comprehensions
Transform and filter a list in a single readable line.
10 min
1 exercise
3 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
You've built many lists like this: start empty, loop, append. A list comprehension does it in one line:
[expression for item in iterable]
Read it as "expression for every item in iterable". The result is a brand new list.
Loop vs comprehension
Both produce the same list. Try [p * 2 for p in prices].
Add an if at the end to keep only some items:
[x for x in items if condition]
Filter and transform
Make a list of only the names that contain the letter "a".
Filtering, one item at a time
for t in temps starts with 18. The test 18 >= 25 is False, so nothing is added to hot.
hot = [t for t in temps if t >= 25]
What does this print?
To choose between two values for every item, put
an if … else expression at the front:
["pass" if s >= 50 else "fail" for s in scores]
Pass or fail
Change the pass mark to 70.
Flatten a grid
Two for clauses read left to right, like nested
loops: for each row, for each number in it.
Two for clauses = nested loops
The outer loop sets row to grid[0]. The inner loop starts on that row: n is 1, so 1 goes into flat.
flat = [n for row in grid for n in row]
What does this print?
Older Python code often uses two built-in functions for the same jobs:
map(func, items): appliesfuncto every item.filter(func, items): keeps the items for whichfunc(item)is True.
Both return a lazy iterator: values are produced only
when you ask for them. print would show an object such
as <map object ...>, so wrap the result in list().
map and filter next to comprehensions
Each pair prints the same thing. Try
print(map(len, words)) to see the lazy object that
map gives back.
What does this print?
Which should you use? Usually a comprehension, since it
reads more clearly. map and filter are handy when a
ready-made function does the job, like
list(map(int, numbers)).
Clean up the data
raw came from a messy form. Using comprehensions:
clean: each entry stripped of spaces and in lower case, skipping entries that are blank.lengths: the length of each word inclean.