⚡ Comprehensions & Iteration, lesson 1 of 5
List comprehensions
Transform and filter a list in a single readable line.
10 min
1 exercise
2 quizzes
0/3 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".
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.
What does this print?
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.