Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Chunk an Iterable into Batches with a Generator in Python
Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.
from itertools import islice
def chunked(iterable, size):
iterator = iter(iterable)
while True:
batch = list(islice(iterator, size))
if not batch:
break
yield batch
if __name__ == "__main__":
data = range(10)
for batch in chunked(data, 3):
print(batch)
Cycle an iterable forever in Python
Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.
def cycle_generator(iterable):
"""Yield items from iterable forever, cycling back to the start."""
items = list(iterable) # Convert to list so it can restart
index = 0
while True:
yield items[index]
index = (index + 1) % len(items)
if __name__ == "__main__":
colors = ["red", "gre…
Drop n items then yield rest generator
A generator that skips the first n items of an iterable and then yields the remaining items one by one.
def drop(n, items):
"""Yield every item except the first n from items."""
it = iter(items)
for _ in range(n):
next(it, None) # skip first n items
yield from it
if __name__ == "__main__":
numbers = [10, 20, 30, 40, 50]
result = list(drop(2, numbers))
print(result)
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 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 Generate Cartesian Product Combinations in Python
Use itertools.product to generate every combination across multiple iterables, a pattern common for product variant generation.
from itertools import product
def generate_cartesian_combinations(*iterables):
"""Generate all Cartesian product combinations of given iterables."""
return list(product(*iterables))
if __name__ == "__main__":
colors = ["red", "green", "blue"]
sizes = ["S", "M", "L"]
styles = ["t-shirt", "hoodie"]…
How to Implement takewhile Generator in Python
A generator that yields items from an iterable until a condition fails, like itertools.takewhile.
def takewhile(predicate, iterable):
for item in iterable:
if not predicate(item):
break
yield item
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
result = list(takewhile(lambda x: x < 4, numbers))
print(result)
How to Lazily Transform Items in Python with a Generator
Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.
def lazy_map(items, transform):
for item in items:
yield transform(item)
def double(x):
return x * 2
def upper(s):
return s.upper()
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
doubled = lazy_map(numbers, double)
print("Doubled numbers:", end=" ")
for value in doubled:
…
How to Merge Multiple Iterables with a Generator in Python
This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.
def chain(*iterables):
for iterable in iterables:
yield from iterable
def main():
list1 = [1, 2, 3]
tuple1 = (4, 5)
set1 = {6, 7}
string1 = "89"
result = list(chain(list1, tuple1, set1, string1))
print(result)
if __name__ == "__main__":
main()
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]
How to Use starmap() to Unpack Tuple Arguments in Python
Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.
from itertools import starmap
def multiply(a, b):
return a * b
if __name__ == "__main__":
pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
results = list(starmap(multiply, pairs))
print(results)
How to filter a generator with a predicate function in Python
This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.
def filter_gen(predicate, iterable):
for item in iterable:
if predicate(item):
yield item
def is_even(num):
return num % 2 == 0
def is_positive(num):
return num > 0
if __name__ == "__main__":
numbers = range(-5, 10)
even_numbers = list(filter_gen(is_even, numbers))
p…
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.