Python - Python Advanced - Iterators Tutorial
An iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets.
The iterator object which implements the iterator protocol is built using the iter() and next() methods.
The iter() function (which in turn calls the __iter__() method) returns an iterator from the iterable objects like lists, tuples, dictionaries, and sets.
The next() function (which in turn calls the __next__() method) is used to manually iterate through all the items of an iterator
Example-
nametuple = ("sam", "sarang", "dinesh", "ashwin")
myit = iter(nametuple)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output-
sam
sarang
dinesh
ashwin
A string is also iterable
Example-
str = "sam"
myit = iter(str)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output-
s
a
m
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Input In [9], in <cell line: 7>()
5 print(next(myit))
6 print(next(myit))
----> 7 print(next(myit))
StopIteration:
It will raise an error if no item is left in the iterator.
__iter__() will work same as iter() and __next__() will work same as next()
Example-
list_data = [10,8,3,5]
my_iter = list_data.__iter__()
print(next(my_iter))
print(my_iter.__next__())
print(next(my_iter))
print(my_iter.__next__())
Output –
10
8
3
5