Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Generate Data with Python Comprehensions and Generators
Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.
# 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
square…
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.
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))
How to Accumulate Values with a Generator in Python
This generator yields the running total of an iterable's elements, producing a cumulative sum with each step.
def accum(iterable):
total = 0
for item in iterable:
total += item
yield total
# Demo
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
print(list(accum(data))) # [1, 3, 6, 10, 15]
# Also works with any iterable, e.g., range
print(list(accum(range(1, 6)))) # [1, 3, 6, 10, 15]
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.
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)
How to Close a Generator and Handle GeneratorExit in Python
This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.
def countdown(n):
try:
while n > 0:
yield n
n -= 1
finally:
print(f"Generator closed after countdown completed")
if __name__ == "__main__":
gen = countdown(5)
print(next(gen))
print(next(gen))
gen.close()
print("Generator closed explicitly")
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.
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")))
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.
"""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…
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.
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)
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.
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…
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.
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]
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.
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…
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.
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)}")
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.
# 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…
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.