Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Iterators

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Iterators

Python Iterators

In Python, iterators allow you to loop through elements in data structures like strings, lists, sets, and more — one item at a time.

To build a custom iterator or use one properly, we need to understand two important methods:

  • __iter__() – Prepares the object to be used as an iterator.

  • __next__() – Returns the next value every time it’s called.

Let’s walk through this step by step.

Using Built-in Iterators

Python automatically provides iterator support for strings, lists, and other collections. You can turn any iterable into an iterator using the built-in iter() function, and loop through it using next().

				
					message = "Arshyan"
iterator = iter(message)

while True:
    try:
        letter = next(iterator)
        print(letter)
    except StopIteration:
        break

				
			

Output:

				
					A
r
s
h
y
a
n

				
			

In this example:

  • iter(message) creates an iterator.

  • next(iterator) gives one character at a time.

  • When all items are used, StopIteration is raised, and the loop stops.

Creating a Custom Iterator

Let’s build our own iterator that returns multiples of 3 up to 30.

				
					class MultiplesOf3:
    def __iter__(self):
        self.num = 0
        return self

    def __next__(self):
        if self.num <= 30:
            result = self.num
            self.num += 3
            return result
        else:
            raise StopIteration

obj = MultiplesOf3()
itr = iter(obj)

for value in itr:
    print(value)


				
			

Output:

				
					0
3
6
9
12
15
18
21
24
27
30

				
			

What’s Going On?

  • __iter__() is called once when the loop starts and sets the initial value.

  • __next__() is called again and again until it hits StopIteration.

  • This gives us full control over what gets returned and when to stop.

Why Use Iterators?

  • They’re memory efficient — great for looping through large datasets.

  • They help you build custom, controllable looping behavior.

  • They give structure to your iteration logic.

Summary

  • Use iter() to create an iterator from a built-in iterable.

  • Use next() to go one step forward.

  • Define __iter__() and __next__() in your class to create your own iterator.

  • Always raise StopIteration to avoid infinite loops.

Scroll to Top