Python Mastery – From Basics to Brilliance / Advanced Python Topics

Generators & Iterators

βœ… What is an Iterator?

An iterator is something you can loop through one item at a time.

πŸ” Think of it like:

A TV remote β€” every time you press the "Next" button (__next__()), it gives you the next channel (value).

πŸ’‘ In Python:

Any object with two methods:

  • __iter__() – returns the iterator object itself

  • __next__() – returns the next item, or throws an error if no more items

πŸ”Ή Example:

numbers = [1, 2, 3]
it = iter(numbers)

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

βœ… What is a Generator?

A generator is a special function that behaves like an iterator.

But instead of returning all values at once, it yields them one at a time.

πŸ” Think of it like:

A water filter that gives one drop at a time when needed β€” instead of filling an entire bucket.


πŸ”§ Generator Example (Improved):

def countdown(n):
    while n > 0:
        yield n  # Pause and give the current value
        n -= 1   # Then continue

# Use the generator
for i in countdown(5):
    print(i)
5
4
3
2
1

βœ… Why Use a Generator?

Feature

Benefit

🧠 Memory efficient

Doesn’t store all values at once

🐒 Lazy evaluation

Only creates values when needed

🧼 Cleaner code

No need to write custom iterator classes

πŸ“ Great for big data

Like reading huge files line-by-line


πŸ” Real-world Example – Reading Large File Line-by-Line

def read_file_lines(filepath):
    with open(filepath, "r") as f:
        for line in f:
            yield line.strip()  # yield each line without loading whole file

for line in read_file_lines("large_file.txt"):
    print(line)

πŸ” Summary Table:

Feature

Iterator

Generator

How created

Using iter() or custom class

Using def + yield

Memory

Can be large if not careful

Very memory efficient

Use Case

Loop over any object

Generate values on-the-fly

Syntax

Needs class with __next__

Just use yield in function