List comprehensions
A list comprehension builds a list in one line:
[expression for item in sequence if condition]
doubled = [n * 2 for n in range(5)] # [0, 2, 4, 6, 8] shout = [w.upper() for w in ["hi", "yo"]] # ['HI', 'YO'] small = [n for n in [5, 1, 8] if n < 6] # [5, 1]
A filter can also use a string: an empty string counts as False, so if r.strip() skips entries that become empty after trimming spaces.
See it run
nums = [1, 2, 3, 4, 5, 6] big = [n * 10 for n in nums if n > 3] print(big)
A comprehension is a loop that builds a new list. Read it as: for each n in nums, keep it only if n > 3, and store n 10*.
Practice list comprehensions
Exercise 1
Using comprehensions:
squares= the squares of 1 to 10evens= the even numbers from 1 to 20
Exercise 2
Use raw in the editor below. With one comprehension, make names: each name stripped of spaces and in title case, skipping entries that are blank.
Expected: ["Ana", "Ben", "Cy"].
Exercise 3
Use prices in the editor below. The café is having a 20% off sale. A dict comprehension works like a list one, with curly braces and key: value:
{k: v * 2 for k, v in d.items()}sale= a new dict with every price 20% off, rounded to 2 decimalscheap= an alphabetically sorted list of items whose sale price is under 4
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.