Reference library

Comprehensions & generators

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

7 matches
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

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

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

Memory efficient map over large file in Python

A generator-based streaming map that processes a large file line by line without loading the whole file into memory.

generator file-io streaming
Python
import sys

def process_lines(file_path):
    """Memory-efficient map over a large file: yields processed lines."""
    with open(file_path, 'r') as f:
        for line in f:
            # Example mapping: strip whitespace and uppercase
            yield line.strip().upper()

if __name__ == "__main__":
    # Use a sma…
12 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.