Python Comprehensions and Generators for Beginners

Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 15 views 0 copies

Python code

39 lines
Python 3.9+
# 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

stdout
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

  1. Use `(n ** 2 for n in range(10))` in a `for` loop to iterate lazily instead of materialising a list.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.