🌱 Junior Track 17 of 18

17. Iterators & Iterables

Understand how Python traverses data behind the scenes: master the Iteration Protocol, `iter()`, `next()`, `StopIteration`, and building custom Iterator classes.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 17 — ITERATORS AND ITERABLES
# ==============================================================================

# 1. Understanding Iterable vs Iterator with iter() and next()
numbers = [10, 20, 30]  # 'numbers' is an Iterable

# Obtain an Iterator object from the Iterable using iter()
iterator = iter(numbers)

print(f"First element: {next(iterator)}")   # Returns 10
print(f"Second element: {next(iterator)}")  # Returns 20
print(f"Third element: {next(iterator)}")   # Returns 30

# Calling next() again raises StopIteration exception
try:
    next(iterator)
except StopIteration:
    print("Caught StopIteration: Iterator is completely exhausted!")


# 2. How Python's 'for' loop works under the hood
def custom_for_loop(iterable):
    it = iter(iterable)
    while True:
        try:
            item = next(it)
            print(f"Manual loop item: {item}")
        except StopIteration:
            break

custom_for_loop(["Python", "Flask", "PostgreSQL"])


# 3. Building a Custom Class that implements the Iterator Protocol
class Counter:
    def __init__(self, low: int, high: int):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        val = self.current
        self.current += 1
        return val

print("Custom Counter Iterator Output:")
for count in Counter(1, 3):
    print(f"Count: {count}")
🌱 Junior Track 17 Master Reference

17. Iteration Protocol Comparison Matrix

📊 Iterable vs Iterator Demystified

Feature Iterable Iterator
Definition An object that can be looped over (e.g. list, dict, str). An object representing a stream of data that delivers values one by one.
Methods Required __iter__() __iter__() and __next__()
Built-in Function iter(iterable) -> iterator next(iterator) -> value
State Tracking Does NOT track iteration position. Tracks current position state in memory.
Reusable? YES (can create multiple independent iterators). NO (exhausts once; raises StopIteration).

⭐ Rate Track 17: Iterators & Iterables (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 16. Standard Library 🌱 Junior Hub 18. Generators →