Python iter() function


Iterators in python iterate sequences, but also iterate objects that exhibit sequence behavior, such as keys in a dictionary, lines in a file, and so on.

An iterator is an object that has a next() method that is not counted by an index. When the next item is needed using a loop mechanism, the iterator's next() method is called, and a StopIteration exception is thrown after the iteration.

But the iterator can only move on, it cannot go back to the beginning, and can only create another new iterative object by iterating again.

Inverted iterator: reversed() will return an iterator that is accessed in reverse order. iterator modules provided in python: itertools module

Related course: Complete Python Programming Course & Exercises

Using Python iter() – A simple Example

Let's look at a few examples of iterators. You can try them in the Python interactive shell. Note that for Python 3 you need __next__() instead of next().

>>> l=[2,3,4]
>>> iterl=iter(l)
>>> iterl.next()
2
>>> iterl.next()
3
>>> iterl.next()
4
>>> iterl.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

python iter function

Another example:

>>> d={'one':1,'two':2,'three':3}
>>>> d
{'three': 3, 'two': 2, 'one': 1}
>>> iterd=iter(d) #The iterator of the dictionary traverses the key of the dictionary
>>> iterd.next()
'three'
>>> iterd.next()
'two'
>>> iterd.next()
'one'
>>> iterd.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

See the following help information for iter() functions.

>>>> help(iter)

Help on built-in function iter in module __builtin__:
iter(...)
    iter(collection) -> iterator
    iter(callable, sentinel) -> iterator

    Get an iterator from an object. In the first form, the argument must
    In the second form, the callable is called until it returns the sentinel.
    In the second form, the callable is called until it returns the sentinel.

Using Python iter() for custom objects

You can add your own iteratable objects, by implementing the __iter__() function in your class.

>>> class test: # test class supports iterative protocols because it defines the __iter__() function
...     def __iter__(self):
...         print '__iter__ is called!'
...         self.result=[1,2,3]
...         return iter(self.result)
... 
>>> t=test() # t supports iterative protocol

>>> for i in t: #When executing for i in t, you are actually calling t.__iter__(), which is __iter__(t), returning an iterator object
...     print i,
... 
__iter__ is called!
1 2 3

>>> for i in t.__iter__():
            print i,

__iter__ is called!
1 2 3
>>> for i in test.__iter__(t):
        print i,

__iter__ is called!
1 2 3


>>> l=[1,2,3]
>>> for i in l:
...     print i,
... 
1 2 3

The above for loop actually works like this (the for loop automatically calls the iterator's next() method), as follows.

>>> iterl=iter(l)
>>> while True:
...     try:
...         i=iterl.next()
...     except StopIteration:
...         StopIteration: ...
...     print i,
... 
1 2 3