Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

11 matches
Comprehensions & generators medium

Build a Generator Pipeline in Python: Filter Then Map

Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.

generators pipeline lazy-evaluation
Python
def read_data():
    return ["a", "bb", "ccc", "dd", "eeeee", "f"]


def filter_short(words):
    return (word for word in words if len(word) >= 2)


def map_to_upper(words):
    return (word.upper() for word in words)


def write_data(words):
    for word in words:
        print(word)


if __name__ == "__main__":
   …
12 0 Open
Comprehensions & generators easy

Build a lazy generator to read file lines in Python

Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.

generator file-io lazy
Python
def lazy_lines(filepath):
    """Yield lines from a file one at a time without loading the whole file into memory."""
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            yield line.rstrip('\n')


if __name__ == "__main__":
    # Create a sample file to demonstrate
    sample_c…
14 0 Open
Comprehensions & generators easy

Dict Comprehension to Map Keys to Lengths in Python

Build a dictionary that maps each word to its character count using a dictionary comprehension.

dictionary comprehension len
Python
words = ["apple", "banana", "cherry", "date", "elderberry"]

word_lengths = {word: len(word) for word in words}

print(word_lengths)
14 0 Open
Comprehensions & generators medium

How to Build a Backpressure Generator Pause Producer Demo in Python

Demonstrates a producer–consumer pattern with a fixed-size buffer that pauses production when full, simulating backpressure.

backpressure producer-consumer deque
Python
import time
import collections

def producer(buffer, max_size, items):
    """Adds items to the buffer until full, then pauses."""
    for item in items:
        while len(buffer) >= max_size:
            print(f"Buffer full ({len(buffer)}/{max_size}) — producer paused")
            time.sleep(0.1)
        buffer.appe…
14 0 Open
Comprehensions & generators easy

How to Build a Sliding Window Generator in Python

Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.

generators sliding-window iteration
Python
def sliding_window(sequence, size):
    for i in range(len(sequence) - size + 1):
        yield sequence[i:i + size]

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    n = 3
    for window in sliding_window(data, n):
        print(window)
12 0 Open
Comprehensions & generators easy

How to Create a Pairwise Generator with zip and tee in Python

Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.

itertools generators zip
Python
from itertools import tee


def pairwise(iterable):
    """Yield successive overlapping pairs from iterable."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5]
    print(list(pairwise(values)))
    print(list(pairwise("hello")))
15 0 Open
Comprehensions & generators easy

How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

generators yield infinite-sequences
Python
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(c…
14 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Comprehensions & generators easy

How to Repeat a Generator Cycle Single Value in Python

Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.

generators loops repeat
Python
def repeat_with_cycle(value, cycle_limit, repetitions):
    """
    Repeats a single value until reaching a cycle limit,
    then yields the value one more time to demonstrate a full cycle.
    
    Args:
        value: The single value to repeat.
        cycle_limit: Number of repetitions per cycle.
        repetitio…
13 0 Open
Comprehensions & generators easy

How to filter even numbers with a Python list comprehension

Build a new list of only the even numbers from 1 to 20 using a single list comprehension with a filter condition.

list comprehension even numbers filtering
Python
even_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)
12 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.