Python Iterators

In Python, iterators are objects that allow you to iterate over a sequence of elements. They are commonly used in loops and are integral to Python's design. In this guide, we'll dive deep into Python iterators, understand how they work, and explore how to create custom iterators. Let's explore iterators in detail!



What is an Iterator?

In Python, an iterator is an object that implements the __iter__() and __next__() methods. An iterator allows you to iterate through a sequence of items, one at a time.

Every iterator in Python is also an iterable, but not every iterable is an iterator. We'll explore the difference in the next section.


Iterators vs Iterable

An iterable is any Python object that can return an iterator. The most common iterables are sequences such as lists, tuples, and strings. An iterator, on the other hand, is an object that tracks the state of the iteration and returns the next item in the sequence when requested via the __next__() method.

The difference is:

  • Iterable: An object that implements the __iter__() method and returns an iterator.
  • Iterator: An object that implements both the __iter__() and __next__() methods.

Example of Iterable:

A list is an example of an iterable:

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

Example of Iterator:

An iterator allows you to use the next() function to fetch the next item in the sequence:

python
my_iterator = iter([1, 2, 3, 4])
print(next(my_iterator))  # Output: 1
print(next(my_iterator))  # Output: 2

Practical Examples of Iterators

Example 1: String Iterator

You can create an iterator from a string and access its characters one by one using the iter() and next() functions.

python
my_string = "abc"
string_iter = iter(my_string)

print(next(string_iter))
print(next(string_iter))
print(next(string_iter))

How It Works:

  • iter(my_string) creates an iterator object from the string.
  • next(string_iter) returns the next character from the iterator.
  • Each call to next() moves to the next character.

Output:

a
b
c

Example 2: List Iterator

Like strings, lists can also be converted into iterators to access each item step by step.

python
my_list = [1, 2, 3]
list_iter = iter(my_list)

print(next(list_iter))
print(next(list_iter))
print(next(list_iter))

How It Works:

  • iter(my_list) returns an iterator from the list.
  • next(list_iter) retrieves the next element in the list.
  • When there are no more items, it will raise a StopIteration error (not shown here).

Output:

1
2
3

Frequently Asked Questions

What is an iterator in Python?

An iterator is an object in Python that enables you to traverse through all the elements of a collection, one at a time, using the __iter__() and __next__() methods.


How do you create an iterator in Python?

You can create an iterator by defining a class with both __iter__() and __next__() methods. You can also get an iterator from any iterable using the built-in iter() function.


What is the difference between iterable and iterator?

An iterable is an object capable of returning its elements one at a time (like a list or tuple). An iterator is the object that actually performs the iteration using next().


Can you loop through an iterator more than once?

No, once an iterator is exhausted, it cannot be reused. You must create a new one if you need to iterate again.


What happens when an iterator is exhausted?

Python raises a StopIteration exception to indicate that there are no more items to retrieve from the iterator.



What's Next?

In the next section, you will learn about Python generators, which provide a simpler and more memory-efficient way of handling iterators. You’ll also learn how to work with Python’s built-in yield function for creating generators.