Python List Comprehension
A list comprehension builds a new list from an existing collection in a single, readable line. It combines a for loop, an optional condition and an expression for each new item. Comprehensions are one of the features that make Python code short and clear, and you will see them everywhere.
From a loop to a comprehension
Here is the same list built twice, first with a loop and then with a comprehension:
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)
squares = [n * n for n in range(1, 6)]
print(squares)[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
Read the comprehension from the middle: "for each n in range(1, 6), take n * n". The square brackets say that the result is a list.
Filtering with if
An if at the end keeps only the items for which the condition is true:
nums = [12, 7, 30, 5, 18, 21]
evens = [n for n in nums if n % 2 == 0]
big = [n for n in nums if n > 10]
words = ["Apple", "kiwi", "Mango", "fig"]
capitals = [w for w in words if w[0].isupper()]
print(evens, big, capitals)[12, 30, 18] [12, 30, 18, 21] ['Apple', 'Mango']
Changing every item
The expression at the front can be anything. With a conditional expression it can even choose between two results for each item:
names = [" asha ", "RAVI", "meera "]
clean = [n.strip().title() for n in names]
print(clean)
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels)
print([len(n) for n in clean])['Asha', 'Ravi', 'Meera'] ['even', 'odd', 'even', 'odd', 'even'] [4, 4, 5]
Notice where the if goes: at the end it filters items; in front, together with else, it chooses a value for each item.
Nested loops, sets and dictionaries
A comprehension can have several for parts, which work like nested loops. Curly brackets make a set or a dictionary in the same way:
pairs = [(x, y) for x in range(1, 3) for y in "ab"]
print(pairs)
print({len(w) for w in ["one", "two", "three"]})
print({w: len(w) for w in ["one", "two", "three"]})[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
{3, 5}
{'one': 3, 'two': 3, 'three': 5}Keep comprehensions short. When one needs several conditions and long expressions, a normal loop is easier to read.
Practice exercises
- Make a list of the cubes of the numbers 1 to 10 with a comprehension.
- From a list of words, keep only those with more than 4 letters, in upper case.
- Make a list of "pass" or "fail" for a list of marks, with 40 as the pass mark.
- Make a dictionary that maps each number from 1 to 5 to its square.