🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#iterators#advanced

Iterators — Under the Hood of Loops

Everything you loop over in Python implements the iterator protocol.


Iterator protocol:

An object is iterable if it has __iter__(). An iterator also has __next__().

my_list = [1, 2, 3]
iterator = iter(my_list)
next(iterator)  # 1
next(iterator)  # 2
next(iterator)  # 3
next(iterator)  # raises StopIteration

Custom iterator:

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for n in Countdown(3):
    print(n)  # 3, 2, 1

Why this matters: Understanding iterators explains how for loops work, why generators are memory-efficient, and how to make your own objects loopable.


YouTube • Top 10
Python Programming: Iterators & the Iterator Protocol
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: Iterators & the Iterator Protocol
Tap to View ›

Reference:

Wikipedia: Iterator

image for linkhttps://en.wikipedia.org/wiki/Iterator

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT