Fundamentals 7 min read

Why Can Python Sequences Be Iterated? Uncover the Magic of iter and __getitem__

This article explains why Python sequences are iterable by detailing how the built‑in iter function, __iter__ and __getitem__ methods work, and shows multiple implementations—including classic iterator classes, generator functions, and generator expressions—to create custom iterable objects.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Can Python Sequences Be Iterated? Uncover the Magic of iter and __getitem__

We all know that sequences are iterable, but why? This article explores the underlying mechanism.

The built‑in iter() function is used by the interpreter: it first checks whether the object implements an __iter__ method; if so, it calls it to obtain an iterator. If not, it looks for a __getitem__ method with integer indexes starting at zero and creates an iterator that accesses elements sequentially. If both checks fail, a TypeError is raised.

An object is therefore iterable when it either provides an __iter__ method that returns an iterator, or a __getitem__ method that supports zero‑based indexing.

Example using __getitem__

class Eg1:
    def __init__(self, text):
        self.text = text
        self.sub_text = text.split(' ')
    def __getitem__(self, index):
        return self.sub_text[index]

o1 = Eg1('Hello, the wonderful new world!')
for i in o1:
    print(i)

Output:

Hello,
the
wonderful
new
world!

We created Eg1 with a __getitem__ method, making its instance o1 iterable.

Example using __iter__

class Eg2:
    def __init__(self, text):
        self.text = text
        self.sub_text = text.split(' ')
    def __iter__(self):
        return Eg2Iterator(self.sub_text)

class Eg2Iterator:
    def __init__(self, sub_text):
        self.sub_text = sub_text
        self.index = 0
    def __next__(self):
        try:
            subtext = self.sub_text[self.index]
        except IndexError:
            raise StopIteration()
        self.index += 1
        return subtext
    def __iter__(self):
        return self

o2 = Eg2('Hello, the wonderful new world!')
for i in o2:
    print(i)

The output is identical to the previous example.

Using a generator with yield

class Eg3:
    def __init__(self, text):
        self.text = text
        self.sub_text = text.split(' ')
    def __iter__(self):
        for item in self.sub_text:
            yield item

This concise implementation leverages the yield keyword, turning the method into a generator function.

Further simplification with yield from

class Eg4:
    def __init__(self, text):
        self.text = text
        self.sub_text = text.split(' ')
    def __iter__(self):
        yield from self.sub_text

Generator expression

class Eg5:
    def __init__(self, text):
        self.text = text
        self.sub_text = text.split(' ')
    def __iter__(self):
        return (item for item in self.sub_text)

In Python, all generators are iterators.

Summary

Iterable objects either implement __iter__ returning an iterator or implement __getitem__ with zero‑based indexing.

Iterators implement a no‑argument __next__ method that raises StopIteration when exhausted and an __iter__ method that returns themselves.

Generator functions contain the yield keyword and produce generator objects.

Generator expressions provide a compact syntax for creating generators without defining a separate function.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

IteratorfundamentalsgeneratorIterableYield
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.