Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
How to Generate Primes with a Generator in Python
Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.
def prime_generator(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return (num for num, is_prime in enumerate(sieve) if is_prime)
if __n…
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…
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.