Python Comprehensions and Generators for Beginners
Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.
Python code
39 lines# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators
def demonstrate_comprehensions():
# List comprehension: squares of even numbers
numbers = range(1, 11)
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# Dict comprehension: number to its factorial
factorial = {}
result = 1
for i in range(1, 6):
result *= i
factorial[i] = result
dict_comp = {k: v for k, v in factorial.items() if k > 2}
# Set comprehension: unique first letters
words = ["apple", "banana", "avocado", "cherry"]
first_letters = {w[0] for w in words}
# Generator expression: sum of squares without storing intermediate list
sum_squares = sum(x * x for x in range(1, 6))
print(f"Even squares: {even_squares}")
print(f"Dict comp (keys > 2): {dict_comp}")
print(f"Unique first letters: {first_letters}")
print(f"Sum of squares (generator): {sum_squares}")
# Generator function example
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
fib_generator = fibonacci(100)
print(f"Fibonacci < 100: {list(fib_generator)}")
if __name__ == "__main__":
demonstrate_comprehensions()
Output
Even squares: [4, 16, 36, 64, 100]
Dict comp (keys > 2): {3: 6, 4: 24, 5: 120}
Unique first letters: {'c', 'a', 'b'}
Sum of squares (generator): 55
Fibonacci < 100: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
How it works
Comprehensions provide a compact syntax for transforming sequences, filtering items with an if clause, and building containers in one expression. A generator expression ((x * x for x in ...)) is lazy — it computes values on demand instead of building a full list in memory, which is why sum() can consume it directly. The set comprehension uses Python's hash-based uniqueness to collapse duplicate first letters into a set. Dict comprehensions let you filter and rebuild key–value pairs in a single pass. Generator functions use yield to produce values one at a time, suspending execution between calls, which is memory-efficient for large or infinite sequences.
Common mistakes
- Confusing a generator expression `(x for x in ...)` with a tuple comprehension — Python has no tuple comprehension; you get a generator instead.
- Forgetting that set comprehensions discard duplicates silently, which may hide data issues.
- Using `[]` instead of `()` for large data — list comprehensions build the whole list in memory before processing.
Variations
- Use `(n ** 2 for n in range(10))` in a `for` loop to iterate lazily instead of materialising a list.
- Apply a conditional `if/else` inside a comprehension: `['even' if n % 2 == 0 else 'odd' for n in range(4)]`.
Real-world use cases
- Transforming API response lists into simplified dicts ready for UI tables or CSV export.
- Streaming log files with a generator function to parse and aggregate stats without loading gigabytes into RAM.
- Deduplicating user email domains from a large dataset with a set comprehension for quick distribution analysis.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.