← Back to list

Python Iterators Explained: Mastering Iteration in Python

Dive into Python iterators with real-world examples. Learn how to create and control your iterators in Python.

codingsprints in Python in Plain English · 2025-04-23 11:31 · 1 claps · 2.0 min read paywalled
#python-iterator #python-iterable #python-next #iter #python-methods
Open on Medium ↗

Python Iterators Explained: Mastering Iteration in Python

Dive into Python iterators with real-world examples. Learn how to create and control your iterators in Python.

Python Iterators

Python Iterators

What is an Iterator in Python?

An iterator is an object in Python that allows you to traverse through all the elements of a collection, one at a time. It implements the iterator protocol, which consists of the **__iter__() and `next()`** methods.

Iterator vs Iterable

Iterable: An object capable of returning its members one at a time (like lists, tuples, sets, dictionaries, and strings).

Iterator: An object with a state that remembers where it is during iteration. It implements **__iter__() and `next()`**.

Example:

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))  # apple
print(next(myit))  # banana
print(next(myit))  # cherry

You can even iterate over a string:

mystr = "banana"
myit = iter(mystr)

print(next(myit))  # b
print(next(myit))  # a
print(next(myit))  # n

Looping Through an Iterator

You can loop through any iterable using a **for** loop, which internally uses an iterator:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
    print(x)

mystr = "banana"

for x in mystr:
    print(x)

Behind the scenes, the **for loop calls `iter()** on the object and usesnext()` Repeatedly until it raises **StopIteration**.

Creating Your Iterator

To create your iterator, define a class that implements both **__iter__() and `next()`**:

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x = self.a
        self.a += 1
        return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))  # 1
print(next(myiter))  # 2

Stopping an Iterator Gracefully

To stop iteration at a certain point, raise the **StopIteration exception inside `next()`**:

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
    print(x) # print 1 to 20

This code prints numbers from 1 to 20 and then stops.

Final Thoughts on Iterators

Iterators are foundational to Python and power many features like loops, comprehensions, and generators. Understanding them will help you write clean, efficient, and Pythonic code.

Master the **__iter__() and __next__() **methods, and you'll have control over how your custom objects behave during iteration.

If you enjoyed this guide, claps and comments are appreciated! 💬👏

Follow CodingSprints for more hands-on Python tutorials.

Happy Coding!

📲 Stay connected: 📘 Facebook | 🐦 Twitter | 💻 GitHub | 🔗 LinkedIn

Thank you for being a part of the community

Before you go:


메타데이터
post_id
9d76962b4f78
slug
python-iterators-explained-mastering-iteration-in-python-9d76962b4f78
url
https://python.plainenglish.io/python-iterators-explained-mastering-iteration-in-python-9d76962b4f78
canonical_url
https://python.plainenglish.io/python-iterators-explained-mastering-iteration-in-python-9d76962b4f78
author_url
https://medium.com/@codingsprints
status
ok
fetched_at
2026-07-20 05:27:41