Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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…
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 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)
Take n items from an infinite Python generator
Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.
from itertools import islice
def count_up_from(start=0):
n = start
while True:
yield n
n += 1
def take_n(generator, count):
return list(islice(generator, count))
if __name__ == "__main__":
gen = count_up_from(10)
result = take_n(gen, 5)
print(result)
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.