Iteration in Python is based upon the iteration protocol which consists of two objects: the iterable and the iterator.
1. Iterable: An iterable is an object (usually a data structure like lists, tuples, sets, dictionaries, etc.) that can be represented as a sequence. It implements the **iter**() method which returns an iterator object or the **getitem**() method for indexed lookup.
1. Iterator: An iterator is an object tied to the iterable which allows traversing through all the elements within the iterable one at a time. It implements the **next**() method which returns the next value from the iterator. If there are no more items to be returned, it raises a StopIteration exception.
Here is how the process works:
a. The iter() built-in function is called on an iterable object which makes it an iterator.
b. The next() built-in function is called on the iterator object to fetch and return the next value. If there is no value left, a StopIteration exception is raised.
c. This process of calling next() repeatedly (often done implicitly within a for loop or list comprehension until a StopIteration exception is encountered and the loop is exited) is what makes up iteration in Python.
Example:
my\_list = [1, 2, 3, 4] my_iter = iter(my_list) print(next(my\_iter)) # Prints 1 print(next(my\_iter)) # Prints 2 #… this can be continued until the iteration endsor,
for i in my\_list: print(i) #… this automatically continues until the iteration ends without explicitly calling next() or worrying about StopIteration.