Reference library

Comprehensions & generators

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

13 matches
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators easy

Group Consecutive Keys in Python with itertools.groupby

Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.

itertools groupby generators
Python
from itertools import groupby

data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]

for key, group in groupby(data):
    group_list = list(group)
    print(f"Key: {key}, Values: {group_list}")
11 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 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 Delegate Iteration to a Subgenerator with yield from in Python

Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.

generators yield-from delegation
Python
def subgenerator():
    yield "first"
    yield "second"
    yield "third"


def delegate():
    yield "before delegation"
    yield from subgenerator()
    yield "after delegation"


if __name__ == "__main__":
    for item in delegate():
        print(item)
13 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 Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

collatz sequence loops
Python
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result…
14 0 Open
Comprehensions & generators easy

How to Implement the Iterator Protocol in Python

A manual iterator class using __iter__ and __next__, compared with an equivalent generator using yield.

iterator generator protocol
Python
class ManualCounter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        value = self.current
        self.current += 1
        return valu…
13 0 Open
Comprehensions & generators easy

How to Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 0 Open
Comprehensions & generators easy

How to Slice a Generator with islice in Python

Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.

itertools islice generators
Python
from itertools import islice


def first_n(iterable, n):
    """Return the first n items from an iterable."""
    return list(islice(iterable, n))


if __name__ == "__main__":
    numbers = range(10, 100)  # large iterable
    result = first_n(numbers, 5)
    print(result)  # [10, 11, 12, 13, 14]
14 0 Open
Comprehensions & generators easy

How to skip items until a condition is met in Python

Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.

itertools generators dropwhile
Python
def is_negative(x):
    return x < 0

numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
13 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 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.