How To Use Python Iterator Example

Iteration is the process of iterating through each element of an object through a for loop. Python’s for syntax is powerful enough to iterate over any object. In python, list / tuple / string / dict / set / bytes are all data types that can be iterated.

1. How To Determine Iterable Object.

You can determine whether an object is iterable use the collections.abc.Iterable module like below.

>>> from collections.abc import Iterable
>>> 
>>> isinstance([1,2,3], Iterable) 
True
>>> isinstance(123, Iterable) 
False
>>> isinstance('abc', Iterable) 
True

If you import Iterable module use codeĀ from collections import Iterable in python 3.8, you will get below error message output.

>>> from collections import Iterable
__main__:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working

2. Python Iterator.

An iterator is an object that can be traversed and can be passed to the next() function. Iterator objects can be used to access the first element of the collection until all elements are accessed.

Iterators can only traverse forward, not backtrack. Unlike lists which you can retrieve the later element at any time, or you can retrieve the previous element by return to the list header.

Iterators usually implement two basic methods: iter() and next(). String, list or tuple objects, and even custom objects can be used to create iterators. Below is an example.

>>> list=['a','b','c','d','e','f']
>>> 
# Use python's built-in iter() method to create iterator object.
>>> it = iter(list)
>>> 
# Use the next() method to get the next element of the iterator.
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
'd'
>>> next(it)
'e'
>>> next(it)
'f'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

You can also traversing iterators using the for loop like below.

>>> list=['a','b','c','d','e','f']
>>> 
# Create iterator object.
>>> it = iter(list)
>>> 
# Iterate over an object using the for loop.
>>> for x in it:
...     
...     print (x, end=" ")
... 
a b c d e f

Most of the time, in order to make your own custom class become an iterator, you need to implement the __iter__() and __next__() methods in the class.