Have you ever wondered how ‘for’ loop is automatically able to iterate over iterable like lists, strings etc? What if I tell you that Python for loop is actually an infinite while loop. Most of us might not believe but as is this beautiful Python.
There must be something inside ‘for’ loop that helps it to iterate over any iterable. In this blog, we will see how the for loop is actually implemented in python. Let’s understand this with an example.
Suppose we want to sum the elements of a list [1,2,3,4]. This can be done as
Actually what happens inside for loop is this
iter_object = iter(my_list)
number = next(iter_object)
To understand this, we first need to know what iterable and iterators are
Iterable: It is anything that you are able to loop over like lists, tuples, strings etc.
Iterator: It is the object that does the actual iterating.
So, in order to iterate, you must first convert an iterable into an iterator. This is done by using built-in iter() function. To get the next item, use next() function on that iterator (not on iterable). If there are 100 elements in an iterable then we need to call next() 100 times. To avoid this, we use an infinite while loop. next() function raises a StopIteration exception when there are no more elements in that iterable. So, to avoid this exception, we have used try-except statement and in this way, we break out from the infinite loop.
This is how the for loop actually works in python.
Now, you might have got some feeling about the Python for loop, iterator and iterable. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.