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 module like below.

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

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 '' 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)
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

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.

0 0 votes
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x