List comprehensions
A list comprehension builds a new list from another collection in a single line. It is one of Python's most loved features.
From loop to comprehension
Here is a loop that builds a list of squares:
Python
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)And the same thing as a comprehension:
Python
squares = [n * n for n in range(1, 6)]
print(squares)Read it as: "a list of n * n, for each n in range(1, 6)".
The pattern is always [expression for item in collection].
More examples
Python
names = ["asha", "leo", "mei"]
print([name.title() for name in names])
print([len(name) for name in names])
prices = [100, 250, 80]
print([round(p * 1.18, 2) for p in prices]) # add 18% taxFiltering with if
Add if at the end to keep only some items:
Python
numbers = [4, 11, 8, 3, 15, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
words = ["apple", "kiwi", "banana", "fig"]
long_words = [w for w in words if len(w) > 4]
print(long_words)Choosing a value with if/else
To transform every item but choose the value, put a conditional expression at the start:
Python
numbers = [4, 11, 8, 3]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)Note the difference:
[x for x in items if condition]filters, so the result can be shorter.[a if condition else b for x in items]transforms, so the result is the same length.
Converting input
Comprehensions are perfect for turning a line of input into numbers:
Python
numbers = [int(x) for x in input().split()]
print(numbers, "sum =", sum(numbers))Nested comprehensions
Python
grid = [[row * col for col in range(1, 4)] for row in range(1, 4)]
print(grid)
flat = [x for row in grid for x in row]
print(flat)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.