Loops are one of the first things we learn as programmers. Especially when you are learning Python, trying out a for loop is one of the first things we’ve done. For loops in Python can be used to iterate over the elements of different data types. For example, we can iterate over strings, lists, tuples, dictionaries, and even files. Have you ever wondered how the for loop is so smart to pick letters from strings, elements from a list, or a tuple, and keys and values from a dictionary?
In this article, let’s discuss in detail how the Python for loop works.
Also, check How to loop over Python dictionaries?
Table of Contents
Working of for loop
Python implements iterator-based loops. Basically, it doesn’t know the underlying object type. No matter what kind of object you pass, like string, lists, tuples, etc. it is not going to determine its type to iterate over it. It checks if the object passed to it is iterable or not. If the object is iterable it asks for the next element, until it reaches the end of the object.
The diagram below summarises the working of a for a loop. When you provide an object in the for loop, the for checks if that object is iterable, if it is not, it throws an error. If the object is iterable, it returns an iterable object. Now, the “for” asks for the next element from the iterator object. The elements are provided one after the other until there are no elements left.
Understanding the working of the for loop programmatically.
Now that we’ve understood the working of for loop, let’s try to figure out, how all of these operations are performed programmatically.
Step 1: First, the object is checked if it is iterable or not using the iter() function
Step 2: If the object is not iterable, iter() raises Typeerror: <data type> object is not iterable.
Step 3: If the object is iterable, an iterator object is returned.
Step 4: For loop, calls the next() function on the iterator object.
Step 5: The iterator object returns the value.
Step 6: Again it calls the next() function, and the iterator object returns another value. This continues until there are no elements left. When there are no elements left, the iterator object raises the Stop Iteration exception. However, this is not visible to the user.
Understanding the working of for loop with examples
Example 1: Iterating over an integer object
Let’s say you have a for loop as shown below:
num=10 for i in num: print(i)
Internally, for calls the iter() function on num as shown below
iter(num)
Since integer objects are not iterable, an error is raised.
TypeError: 'int' object is not iterable
Let’s see what happens when we run the below code.
num=10 for i in num: print(i)
Output: As discussed, we saw the below error.
Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 2, in <module> for i in num: TypeError: 'int' object is not iterable
Example 2: Iterating over a list object
Let’s say, you have to loop over a list object.
num_list= [1,2,3,4,5] for i in num_list: print(i)
Internally, for calls the iter() function on num_list and, it returns an iterator object.
iter(num_list) <list_iterator object at 0x0000021CBBC58E20>
Now, for loop calls the next() function to determine the next element from the iterator object until throws the StopIteration exception.
>>num_list_iterator=iter(num_list) >>print(next(num_list_iterator)) 1 >>print(next(num_list_iterator)) 2 >>print(next(num_list_iterator)) 3 >>print(next(num_list_iterator)) 4 >>print(next(num_list_iterator)) 5 >>print(next(num_list_iterator)) Traceback (most recent call last): File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> StopIteration
Let’s run the code in IDE and see the output:
num_list= [1,2,3,4,5] for i in num_list: print(i)
Output:
1 2 3 4 5
Example 3: Iterating over the string object
Let’s say we have to loop over a string as shown below:
my_str="Hello" for i in my_str: print(i)
Internally, for calls the iter() function on my_str and, it returns an iterator object.
>>iter(my_str) <str_iterator object at 0x0000021CBBC59EA0>
Now, for calls the next() function on the iterator object unttill StopIteration exceptions is raised.
>>my_str_iterator=iter(my_str) >>print(next(my_str_iterator)) H >>print(next(my_str_iterator)) e >>print(next(my_str_iterator)) l >>print(next(my_str_iterator)) l >>print(next(my_str_iterator)) o print(next(my_str_iterator)) Traceback (most recent call last): File "C:\Users\paian\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> StopIteration
However, all this happens internally. Thus, we can see the characters of the string printed when we run the below code.
my_str="Hello" for i in my_str: print(i)
Output:
H e l l o
What if you want to get to the beginning of the loop after iterating once?
Note that the for loop can only access the next elements and cannot go back. Also, there’s no way to reset the loop. The only way to get to the beginning of the loop is by calling the for loop again.
That’s all.
We hope this article has been informative. Kindly comment and let us know if this helped. Do come back to us for more interesting content. Thanks for reading.