Table of Contents
In this article, I will take you through the Concepts of Iterator in Python Explained with Best Examples. Iterator is very handy in iterating over the list, tuples, dict, set etc. in python hence it plays an important role in Python Scripting. Iteration is fundamental to data processing - programs mostly apply computations to data series, from pixels to nucleotides. If the data does not fit in memory, we need to fetch the items lazily - one at a time and on demand. That’s what an iterator does. This article shows how the Iterator pattern is built into the Python language so you never need to code it by hand.
Every collection in Python is iterable, and iterators are used internally to support:-
- for loops
- Collection types construction and extension
- Looping over text files line by line
- List, dict, and set comprehensions
- Tuple unpacking
- Unpacking actual parameters with * in function calls
Why Sequences are Iterable
Whenever the interpreter needs to iterate over an object x, it automatically calls iter(x)
.
The iter
built-in function:
- Checks whether the object implements
__iter__
, and calls that to obtain an iterator. - If
__iter__
is not implemented, but__getitem__
is implemented, Python creates an iterator that attempts to fetch items in order, starting from index 0 (zero). - If that fails, Python raises TypeError, usually saying
“C object is not iterable,”
where C is the class of the target object.
Iterable vs Iterator
Any object from which the iter built-in function can obtain an iterator. Objects implementing an __iter__
method returning an iterator are iterable. Sequences are always iterable; as are objects implementing a __getitem__
method that takes 0-based indexes. It’s important to be clear about the relationship between iterables
and iterators
: Python obtains iterators
from iterables
. Check more about Iterator in Python on Fluent Python.
Using Iterator in Python Explained with 3 Best Examples
Also Read: Concept of Data Encapsulation in Python Explained with Best Examples
In python, iterators are objects that can be iterated upon. lists, dictionary, tuples and sets in python are all iterable objects.
All iterator objects uses two exclusive functions. They are:-
iter() -> which is used for initializing iterator object. It internally calls the method __iter__()
next() -> which is used for iteration i.e iterate all the items of iterator one by one. In python3, we can use __next__()
instead.
Above two methods are collectively called as iterator protocol
.
Example 1: Python in-built iterator
mylist= [3,2,4,'Hi']
mystring= 'cyberithub'
iterobject1= iter(mystring)
iterobject= iter(mylist)
print(next(iterobject)) #returns 1 item at a time
#print(iterobject.__next__()) # use iterobject.__next__() in python3
for i in iterobject: #iterate complete list right from the next element
print(i)
for j in iterobject1:
print(j)
Program Output
[root@localhost ~]# python example.py 3 2 4 Hi c y b e r i t h u b
Example 2: Using try-except block in Python
mystring= 'cyberithub'
iterobject= iter(mystring)
while True:
try:
print(next(iterobject))
for i in iterobject:
print(i)
except StopIteration:
print("This is the end of list")
break
Program Output
[root@localhost ~]# python example.py c y b e r i t h u b This is the end of list
NOTE:
it.__next__()
in Python 3
and it.next()
in Python 2
. As usual, you should avoid calling special methods directly. Just use the next(it)
: this built-in function does the right thing in Python 2 and 3Example 3: Using Custom build iterators in Python
class Number:
def __init__(self, max):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.max>= self.n:
result =self.max**2
self.max -= 1
return result
else:
raise StopIteration
ob = Number(6)
x = iter(ob)
print(next(x))
print(next(x))
for i in x:
print(i)
Program Output
[root@localhost ~]# python3.6 example.py 36 25 16 9 4 1 0
Popular Recommendations:-
Inheritance Concepts and Its 5 Different Types in Python with Examples
How to List all the Installed Modules in Linux{2 Easy Methods}
Solved: ModuleNotFoundError No module named "numpy" in Python3
Python3: ModuleNotFoundError No module named "prettytable" in Linux
Solved: ModuleNotFoundError No module named "requests" in Python3