Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Python
Python Generators and Iterators

Python Generators and Iterators

Python2,026 viewsBy Admin
pythongeneratorsiterators

Advertisement

Iterators and Generators

Generators produce values lazily, one at a time, instead of building a whole list in memory. Perfect for huge or infinite sequences.

A Generator with yield

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for num in countdown(3):
    print(num)  # 3, 2, 1

Why It Saves Memory

# List — stores ALL 10 million numbers in RAM
nums = [n for n in range(10_000_000)]

# Generator — stores ONE number at a time
nums = (n for n in range(10_000_000))

Infinite Generators

def infinite_ids():
    i = 1
    while True:
        yield i
        i += 1

Reading a Huge File Lazily

def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.strip()
# Processes a 50GB file with tiny memory

FAQs

Generator vs list — when to use which?

Use a list when you need random access or to reuse data. Use a generator for one-pass, large, or streaming data.

Can I reuse a generator?

No — once exhausted it's done. Create a new one. More in our Python section.

Advertisement