Generate Data with Python Comprehensions and Generators

Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.

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

Python code

33 lines
Python 3.9+
# Data generation helpers using comprehensions and generators
from itertools import islice


def fibonacci(limit):
    """Generate Fibonacci numbers up to a limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


def main():
    # List comprehension: squares of even numbers
    squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
    print(f"Even squares: {squares}")

    # Dictionary comprehension: number -> its cube
    cubes = {x: x ** 3 for x in range(1, 6)}
    print(f"Cubes dict: {cubes}")

    # Generator expression: filter odd numbers, take first 5
    odds = (x for x in range(1, 100) if x % 2 != 0)
    first_five_odds = list(islice(odds, 5))
    print(f"First 5 odds: {first_five_odds}")

    # Use the fibonacci generator
    fib_numbers = list(fibonacci(50))
    print(f"Fibonacci up to 50: {fib_numbers}")


if __name__ == "__main__":
    main()

Output

stdout
Even squares: [4, 16, 36, 64, 100]
Cubes dict: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
First 5 odds: [1, 3, 5, 7, 9]
Fibonacci up to 50: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

How it works

List comprehensions build a full list in memory, while generator expressions produce items lazily, saving memory for large data. The dictionary comprehension constructs a key-value mapping directly. The fibonacci function uses yield to create a generator that produces values on demand, ideal for infinite sequences. Using itertools.islice limits the generator to the first five odd numbers without consuming the whole range.

Common mistakes

  • Forgetting parentheses around generator expressions when outputting to list()
  • Using a list comprehension when a generator would save memory for large data
  • Not resetting a generator before iterating it again—it gets exhausted
  • Missing the `yield` keyword in a generator function, turning it into a regular return

Variations

  1. Use a set comprehension `{x for x in range(10)}` to get unique values
  2. Use `range(1, 100, 2)` to generate odds directly without filtering

Real-world use cases

  • Creating lookup tables by mapping IDs to computed values for quick access in production code.
  • Generating test data streams lazily for performance testing without loading everything into memory.
  • Feeding an infinite Fibonacci sequence to algorithms that need a tail of the series.

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.