Fundamentals 7 min read

Why Can Python Sequences Be Iterated? Understanding iter, __getitem__, and Generators

This article explains how Python determines whether an object is iterable by using the built‑in iter function, detailing the roles of __iter__, __getitem__, iterator protocols, and showing concise implementations with generators and generator expressions.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Can Python Sequences Be Iterated? Understanding iter, __getitem__, and Generators

We all know that Python sequences are iterable, but the underlying mechanism involves the built‑in iter() function.

The interpreter calls iter(x) which works in three steps: (1) if x implements __iter__, it is called to obtain an iterator; (2) otherwise, if x implements __getitem__ with zero‑based indexing, Python creates an iterator that accesses items sequentially; (3) if neither is present, a TypeError is raised.

An object is therefore iterable when it either defines __iter__ or defines __getitem__ with integer indices starting at 0.

Example 1 shows a class Eg1 that implements __getitem__. The instance o1 = Eg1('Hello, the wonderful new world!') can be used in a for loop, producing each word.

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)

Example 2 implements the iterator protocol with a separate iterator class Eg2Iterator. Eg2.__iter__ returns an Eg2Iterator instance, which defines __next__ and raises StopIteration when exhausted.

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)

Using a generator simplifies the implementation. Example 3 defines Eg3.__iter__ as a generator that yields each word.

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

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

Example 4 uses yield from to delegate to the underlying list.

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

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

Example 5 demonstrates a generator expression inside __iter__.

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)

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

Key takeaways:

An iterable implements __iter__ or __getitem__ with zero‑based indexing.

An iterator implements a zero‑argument __next__ that returns the next element or raises StopIteration, and __iter__ that returns itself.

A generator is a function containing yield; calling it returns a generator object, which is also an iterator.

A generator expression provides a concise syntax to create a generator 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.

PythonIteratoriterationgeneratorIterable
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.