Understanding List Comprehensions & Generator Expressions in Python
Python provides elegant and compact tools to build new sequences from existing iterables. List Comprehensions and Generator Expressions offer clean syntax, improved readability, and performance benefits — especially for data processing and functional-style programming.
What is a List Comprehension?
A list comprehension creates a new list by applying an expression to each item in an iterable. It is a shorter and often faster alternative to traditional loops.
# Traditional loop
squares = []
for n in range(5):
squares.append(n*n)
# List comprehension
squares = [n*n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]With conditions
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]What is a Generator Expression?
Generator expressions look similar to list comprehensions but use () instead of []. They return a generator object and produce elements on demand, saving memory for large datasets.
# Generator expression
gen = (n*n for n in range(1000000))
print(gen) #
print(next(gen)) # 0
print(next(gen)) # 1Key point: Generator expressions do not store all values in memory at once.
List Comprehension vs Generator Expression
| Feature | List Comprehension | Generator Expression |
| Output | List | Generator (lazy evaluation) |
| Memory usage | High for large data | Very low |
| Speed for small data | Often faster | Slightly slower |
| Use case | Need full list output | Streaming, large data processing |
Where to Use Each?
- List Comprehension: When you need the complete list immediately.
- Generator Expression: When processing large data, pipelines, or reading files.
Example: reading large file efficiently
total = sum(int(line) for line in open("numbers.txt"))
print(total)Nested Comprehensions
matrix = [[1,2,3],[4,5,6]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6]Conclusion
List comprehensions and generator expressions are powerful tools for clean and efficient Python. Choose comprehensions for immediate collections, generators for scalable streaming operations.