Iterators:
- Collection data types always an important concept in Python.
- We iterate the data of collection object using iterators
- Iterator in Python is simply an object that can be iterated upon.
- An object which will return data, one element at a time.
- The two methods __iter__() and __next__() are used to iterate an object.
- An object is called iterable if we can get an iterator from it. Most of built-in containers in Python like: list, tuple, string etc. are iterables.
my_list = [4, 7, 0, 3]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)
We can easily iterate the collection object elements using for loop as follows:
for element in iterable:
# do something with element
It is actually implemented as:
# create an iterator object from that iterable
iter_obj = iter(iterable)
# infinite loop
while True:
try:
# get the next item
element = next(iter_obj)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
- So internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable.
- Ironically, this for loop is actually an infinite while loop.