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…
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.
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…
How to Repeat a Generator Cycle Single Value in Python
Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.
def repeat_with_cycle(value, cycle_limit, repetitions):
"""
Repeats a single value until reaching a cycle limit,
then yields the value one more time to demonstrate a full cycle.
Args:
value: The single value to repeat.
cycle_limit: Number of repetitions per cycle.
repetitio…
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.