Python List Comprehension: Transform and Filter Lists
A list comprehension builds a new list from another one in one line, such as [name.upper() for name in names]. It can change every item, keep some, or both.
Read For loops and Lists first.
Change every item in a list
Write what you want for each item, then a for that says where the items
come from. Put it all inside square brackets.
prices = [4, 10, 7]
doubled = [price * 2 for price in prices]
print(doubled)
print(prices)
Read it as "price * 2 for each price in prices". The result is a new
list. prices itself does not change.
List comprehension vs for loop
A comprehension replaces three steps: make an empty list, loop, and
append().
scores = [12, 7, 15]
bonus = []
for score in scores:
bonus.append(score + 5)
print(bonus)
print([score + 5 for score in scores])
Both lines print [17, 12, 20]. The comprehension says the same thing in
one line.
Filter a list with if
Add if at the end to keep only the items that pass a test.
scores = [12, 4, 19, 7, 15]
passed = [score for score in scores if score >= 10]
print(passed)
4 and 7 fail the test, so they are left out. The order stays the same.
Filter and transform in one step
Use both parts at once. The if picks the items, then the front part
changes them.
words = ["apple", "fig", "banana", "kiwi", "yam"]
long_words = [word.upper() for word in words if len(word) > 3]
print(long_words)
"fig" and "yam" are too short. The other three come out in capitals.
if-else in a list comprehension
To choose between two values for every item, put if ... else at the
front, before the for.
rolls = [3, 6, 1, 6]
labels = ["six" if roll == 6 else "miss" for roll in rolls]
print(labels)
Nothing is dropped here: each roll becomes "six" or "miss". A filtering
if goes at the end. A choosing if ... else goes at the front.
Note: Keep comprehensions short. When one needs several conditions or a
loop inside a loop, a normal for loop is easier to read.
See also: map() and filter(), Dictionary comprehension, The accumulator pattern.
Your turn
Build a list of the squares of the even numbers in numbers, then print
it.
numbers = [1, 2, 3, 4, 5, 6]
# add two lines: build the list with a comprehension, then print it
Expected output
[4, 16, 36]