Comprehensions and generator expressions
More Python9 min readLesson 1 of 7
1.1 One expression instead of a loop
A list comprehension builds a list from an iterable in a single expression: square brackets, an expression for each item, then a for clause, optionally followed by an if filter. It is not faster than a well-written loop, but it says what is happening without an index variable.
Swap the square brackets for parentheses and you get a generator expression. It produces values on demand instead of building the whole list, which matters when the data is large or the first few values are all you need.
squares = [n * n for n in range(1, 6)]
print(squares)
evens = [n for n in squares if n % 2 == 0]
print(evens)
total = sum(n * n for n in range(1, 6))
print(total)Output
[1, 4, 9, 16, 25] [4, 16] 55
Use comprehensions for a single transformation or filter. If the expression needs nested loops and two conditions, a normal loop with a name is easier to read a month later.
