Reading Time: 1 minutes
Using iter() in Python - The Iteration Protocol in Python
Sequences and file handlers in Python have an __iter__() magic method. When the sequence is used is in conjunction with a for loop, the __iter__() method of the sequence calls the builtin iter() method and returns an iterator object. This is called the 'The Iterator Protocol'. The iterator object thus received, has a __next__() method, which gives the element in the sequence. When there is no element left and the __next__() method is called, the iterator object raises a StopIteration exception.
>>> numbersListIterator = iter([1, 2, 3]) >>> numbersListIterator <listiterator object at 0x03040830> >>> numbersListIterator.__next__() 1 >>> numbersListIterator.__next__() 2 >>> numbersListIterator.__next__() 3 >>> numbersListIterator.__next__() Traceback (most recent call last): numbersListIterator.__next__() StopIteration
Once you have an iterator object, you can iterate over the values in the following 3 ways:
- Using the __next__() magic function of the iterator object, as done above. The __next__() is calling the builtin next() method and passing itself (i.e. numbersListIterator) to it.
- Using the builtin next() function explicitly, such as next(numbersListIterator).
- Using a for loop, such as for number in numbersListIterator: print(number).