Python List Comprehension
Python list comprehension is a short, readable way to create a new list from an existing sequence. Instead of creating an empty list and appending inside a for loop, you describe the whole list in one expression inside square brackets.
From for Loop to List Comprehension
Both versions below build the same list of squares. The comprehension reads as "n squared for each n in the range".
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]
Filtering with if
Add an if at the end to keep only the items that pass a test.
words = ["data", "AI", "python", "web", "cloud"]
long_words = [w for w in words if len(w) > 3]
print(long_words)
shouted = [w.upper() for w in words if "o" in w]
print(shouted)['data', 'python', 'cloud'] ['PYTHON', 'CLOUD']
List Comprehension with if else
To transform every item in one of two ways, put a conditional expression at the start. Note the position: if else goes before for, while a filter-only if goes after.
stock = [120, 0, 45, 0, 300]
labels = ["available" if s > 0 else "sold out" for s in stock]
print(labels)['available', 'sold out', 'available', 'sold out', 'available']
Nested Comprehensions
Several for clauses run like nested loops, left to right. A common use is flattening a list of lists.
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat)
pairs = [(a, b) for a in "xy" for b in range(2)]
print(pairs)[1, 2, 3, 4, 5, 6]
[('x', 0), ('x', 1), ('y', 0), ('y', 1)]Dictionary and Set Comprehensions
The same idea works with curly braces. key: value pairs make a dictionary, single values make a set.
names = ["Ali", "Sara", "Emma"]
lengths = {name: len(name) for name in names}
print(lengths)
initials = {name[0] for name in names}
print(sorted(initials)){'Ali': 3, 'Sara': 4, 'Emma': 4}
['A', 'E', 'S']Generator Expressions
With round brackets you get a generator expression, which produces values one at a time instead of building a full list in memory. It is ideal inside functions like sum(), max() or any().
total = sum(n * n for n in range(1, 1001))
print(total)
print(any(n > 100 for n in [5, 50, 500]))333833500 True
Comprehensions are great for simple transformations. If yours needs several conditions or nested logic that is hard to read on one line, a regular for loop is the better choice.
Frequently asked questions
Is list comprehension faster than a for loop?
Usually a little faster, because the appending happens inside optimised C code. The main benefit, though, is shorter and clearer code.
How do I use if else in a list comprehension?
Put the conditional expression before the for: [x if x > 0 else 0 for x in nums]. A plain filter if goes after the for.
What is the difference between a list comprehension and a generator expression?
A list comprehension uses square brackets and builds the whole list immediately. A generator expression uses parentheses and produces items lazily, saving memory.