A list comprehension builds a new list in one line. It is a shorter way to write the very common pattern "start with an empty list, loop, append". Once it clicks, you will see it everywhere in Python code.
FROM LOOP TO ONE LINE
The long way:
squares = []
for n in range(5):
squares.append(n * n)
print(squares)[0, 1, 4, 9, 16]
The same thing as a comprehension:
squares = [n * n for n in range(5)]
print(squares)[0, 1, 4, 9, 16]
Read it as: "n times n, for every n in range(5)". The part before for is what goes into the new list.
WITH A FILTER
scores = [12, 55, 7, 80, 33]
high = [s for s in scores if s >= 30]
print(high)[55, 80, 33]
The if at the end keeps only the items that pass the test.
CHANGING TEXT
names = ["ana", "ivo", "mia"]
print([name.title() for name in names])
print([len(name) for name in names])['Ana', 'Ivo', 'Mia']
[3, 3, 3]
IF/ELSE INSIDE
To change each item depending on a condition (instead of filtering), put the if/else before the for:
hp = [10, 0, 4]
print(["alive" if h > 0 else "down" for h in hp])['alive', 'down', 'alive']
DICTIONARY COMPREHENSIONS
words = ["snek", "py", "arcade"]
lengths = {w: len(w) for w in words}
print(lengths){'snek': 4, 'py': 2, 'arcade': 6}
print([x * 2 for x in range(1, 6) if x % 2 == 1])WHEN NOT TO USE ONE
for loop is clearer. Short and simple is the goal.[x for x in a if x > 0] filters. [x if x > 0 else 0 for x in a] changes.PRACTICE IT, DON'T JUST READ IT
Loop Lagoon in Snekcade drills loops and lists with quick swipes and real code. It is free to play.
PLAY LOOP LAGOON ▸FAQ
What is a list comprehension in Python?
A short way to build a list: [expression for item in collection if condition].
Where does the if go in a list comprehension?
A filter goes at the end: [x for x in a if x > 0]. An if/else that changes values goes at the front: [x if x > 0 else 0 for x in a].
Are list comprehensions faster than loops?
Usually a little, but the main reason to use them is that short ones are easier to read.