logo

Understanding Iterators in Python

O

Ohidur Rahman Bappy

MAR 22, 2025

Understanding Iterators in Python

In this post, we will dive into the concept of iterators and the iter() function in Python.

What Are Iterators?

Iterators are used implicitly when handling collections like lists, tuples, or strings—often referred to as iterables. A common way to traverse a collection is using a for loop:

my_list = [1, 2, 3, 4]
for item in my_list:
    print(item)

Output:

1
2
3
4

Here, the for loop automatically uses an iterator to go through the elements of my_list.

Using iter() Function

Alternatively, you can traverse an iterable without a for loop by using the iter() function. An iterator is an object that represents a stream of data, returning one element at a time using the __next__() method.

def traverse(iterable):
    it = iter(iterable)
    while True:
        try:
            item = next(it)
            print(item)
        except StopIteration:
            break

Example with iter() and next

The iter() function can be used directly to create an iterator object from an iterable:

L1 = [1, 2, 3]
it = iter(L1)
print(it.__next__())  # Output: 1
print(it.__next__())  # Output: 2
print(it.__next__())  # Output: 3

When you reach the end of the iterable, __next__() raises a StopIteration exception:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    it.__next__()
StopIteration

Using next() for Iteration

Instead of repeatedly calling __next__(), you can use the built-in next() function, which simplifies the syntax:

L1 = [1, 2, 3]
it = iter(L1)
print(next(it))  # Output: 1
print(next(it))  # Output: 2
print(next(it))  # Output: 3

Note: If you attempt to iterate over a non-iterable, such as an integer, Python throws a TypeError:

>>>iter(100)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    iter(100)
TypeError: 'int' object is not iterable

Limitations and Generators

A limitation of using iterators is that they raise an exception when there are no more items. You can overcome this by creating your own iterator functions using generators.

By understanding iterators and how to use the iter() function, you can efficiently handle sequences and streams of data in Python, adding flexibility and power to your programming toolkit.