Python iter: How to Convert Iterable to Iterator

The iter() method returns the iterator for the provided object. The iter() method creates the object which can be iterated one element at a time.

Python iter

Python iter() is a built-in function that converts an iterable to an iterator. It offers another way to iterate the container. To access iter() function’s elements. iter() uses next() for obtaining values.

These objects are useful when we couple with the loops like for loop and while loop.

The iteration object remembers an iteration count via an internal count variable.

Once the iteration is finished, it raises the StopIteration exception, and the iteration count cannot be reassigned to 0.

Therefore, it can be used to traverse a container just once.


The syntax of the iter() method is the following.

iter(object, sentinel)


Object: It is an object whose iterator must be created (can be settuple, list, dictionaries, etc.).

sentinel (Optional) – It is the special value used to represent the end of a sequence.

See the following example.


data = iter(['millie', 'finn', 'gaten', 'caleb'])


We passed a list to the iter() function in the above code and printed the item using the Python next() function.

How iter() works for custom objects

Okay, now let’s define the custom object and then iterate that object using the next() function.


class Display:
    def __init__(self, count):
        self.count = count

    def __iter__(self): = 0
        return self

    def __next__(self):
        if( >= self.count):
            raise StopIteration += 1

num = Display(2)

printData = iter(num)

# prints '1'

# prints '2'

# raises StopIteration

See the output.

➜  pyt python3
Traceback (most recent call last):
  File "", line 26, in <module>
  File "", line 11, in __next__
    raise StopIteration
➜  pyt

Iteration is a generic term for taking each element of something, one after another. Any time you use the explicit or implicit loop to go over the group of items that is an iteration.

In Python, iterable and iterator have precise meanings.

The iterable is an object with an __iter__ method that returns an iterator or describes the __getitem__ method that can take the sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid).

So the iterable is an object that you can get an iterator from.

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

Whenever you practice a for loop, map, or list comprehension, etc.,

In Python, the next() method is called automatically to get all items from an iterator, going through the iteration process.

That’s it for this tutorial.

1 thought on “Python iter: How to Convert Iterable to Iterator”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.