Latest Code Tutorials

Python iter: How to Convert Iterable to Iterator

Python iter() is an inbuilt function that is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object. The iter() method creates the object which can be iterated one item at a time.

Python iter() Example

These objects are useful when we coupled with the loops like for loopwhile loop.

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

Once the iteration is finished, it raises the StopIteration exception and 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 has to be created (can be setstuples, lists, dictionaries, etc.)

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

See the following example.


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


In the above code, we have passed a list to the iter() function and then print the item one by one 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 loop, explicit or implicit, to go over the group of items, that is an iteration.

In Python, iterable and iterator have precise meanings.

The iterable is an object that has an __iter__ method that returns an iterator, or which 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, or map, or a list comprehension, etc. in Python, the next() method is called automatically to get all items from an iterator, therefore going through the process of iteration.

Finally, Python iter() Example Tutorial is over.

1 Comment
  1. Amit Parmar says

    Thanks for the post

Leave A Reply

Your email address will not be published.

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