For Loop in Python
Video Tutorial
Overview
Iterating over a sequence is done using a for loop in Python(that is either a list, a tuple, a dictionary, a set, or a string). This functions more like an iterator method found in other object-oriented programming languages than the for loop in other programming languages.
Scope of the Article
- In this blog, we will learn about for loops in Python, their syntaxes, internal working along with suitable examples.
- We will also look at different ways to use for loop over different data structures.
- In the end we will learn about break, pass, and continue statements.
What is the need of For loop in Python
Suppose you want to play your favorite song on repeat mode. You will do that by tapping the repeat button in the music player app. So by doing this, you are just looping over your favorite song repeatedly. The repeat button provides this looping functionality by implementing the for loop smartly. Behind the scenes, the loop has enabled the song to be played repeatedly any number of times you want on repeat mode.
In Python, we have a for loop that is used to iterate over a sequence (in the case of the song, the sequence can be the list, tuple, etc., of the music bits stream). There are other loops, too, using which we can iterate over the sequences like list, tuple, set, dictionary, etc., but a for loop makes it much easier as we need not manage any loop variables. Using a for loop in python, we can execute a set of statements on each item of a list, set, dictionary or tuple.
Let us see the syntax for the for loop in python along with an example.
Syntax of for loop in Python
Above val is an iterator variable that takes the value of each item from the sequence on each iteration. After taking the value in val, the loop body executes. for loop continues until the last item of the sequence is reached.
Flowchart of For loop in Python
Example of Python for Loop
Let’s see a python program that uses a for loop to iterate over a list. First, the for loop iterates over each item of the list and takes it in the variable val. Now the body of the loop gets executed where it is checked whether the number is even or not. If the number is even, then the count variable is incremented. The program then prints the frequency of the even numbers present in the list. You can see here that the for loop has reduced our effort of writing the same line of code again and again for different items in the list.
Output:
How For Loop in Python Works Internally?
To understand how for loops work internally, you must have a good understanding of iterators in Python. You must know the difference between the iterable and iterator. First, let’s see these terms.
- Iterable: It is an object in Python in which iter() or getitem() methods are defined. On a higher level, if something is iterable, then it simply means that it can be looped over. If something is iterable or can be looped over, then it must have iter() method. For example, list, tuple, dictionary, set, or strings are all iterables.
- Iterator: Iterator is a Python object with a state such that it remembers where it is during the iterations. Also, the iterator has the next() method defined which helps to fetch consecutive elements stored one after the other in the iterable.
In short, Iterable is a sequence or a series of elements that can be iterated over, and an iterator keeps track of the elements of iterable and lets us check if it has more elements and helps to move to the next element(if any) in the series.
For loops in python are used to iterate over any iterable objects (For example, list, tuple, dictionary, set, or string).
Output:
Let’s deep dive into it using the above example and understand what actually happens internally with the python for a loop.
In the above code, we have iterated over a list ‘country’ using the for loop and printed each element stored in it. Now with the below steps and the same code example as above, we will understand the entire process. We will see how the above code gets executed by python by using the different objects and methods. To carry out the iterations of the for loop, python does the following internally.
- Using iter() method makes the list iterable.
- Run an infinite while loop until StopIteration exception is raised. StopIteration is raised by next() method or using next() when all items get exhausted.
- Fetch the next item in the try block and print it.
- If the StopIteration exception is encountered, break the loop.
Output:
In the above example, we can see that in the background, that iter() and next() methods are called to iterate over an iterable. When we use a for loop to traverse any sequence or object which is iterable, internally, the iter() method is being used to get an iterator object. Now, this iterator object uses the next() method to iterate over the iterable.
Hope you have now got a pretty clear idea about the internal working of the python for loop.
The range() function
range() is a built-in function provided by Python. This function is commonly used with a for loop for looping over a range of numbers. This function returns a sequence of numbers that, by default, starts with zero, increments by 1, and ends at a specified number passed as an argument. However, it is possible to provide this function as an argument for the starting number, increment step size, and the number at which it needs to stop. There are three ways in which a range() function can be used:
- range(stop): It takes one argument and is the default version of the range() function. It will generate a sequence of numbers starting from 0, incrementing by 1, and ending at the specified number count. For example, range(15) will generate the numbers starting at 0 and ending at 14.
- range(start, stop): This will take as an argument the starting and the ending numbers and will generate the sequence incrementing by 1. For example,
- range(5, 10) will generate a sequence of numbers starting at 5 and ending at 9, by default incremented by 1.
- range(start, increment, stop): This version takes the start value, step value by which the series will increment(positive integer) or decrement(negative integer), and ending values parameters and generates the sequence. For example,
- range(6, 2, 21) will generate all the even numbers between 6 and 21. There will be an increment of 2 in successive values as the step size is 2.
To iterate through a list, range() is generally used in combination with the len() function. Also, while using the range() we will be accessing the items stored in the sequence by indexing.
Now, let’s understand with an example how we can use range() with the for loop in python. In the below code, we are using the for loop to iterate over a list containing the cities using the range() function. Since range() needs to be given at least one argument, i.e, the stop value, the stop value will be the size of the list as we want to print all the cities concatenating with the “I Love” string. So the loop will go through each integer starting from 0 to end (which is the list size), and using indexing, the city name from the list will be printed.
Output:
Python For loop with else
In Python, we can have an optional else block with the for loop. The statements in the else block are executed when the for loop exhausts. However, the else block will never execute if the for loop is terminated by the break statement. Therefore, the else part of the for loop will only get executed if the break does not occur.
A question might come to your mind instead of using else with if, what is the need for using the else clause with the python for a loop. Imagine you are writing a program for finding whether a value is present in a sequence or not. So when the loop exhausts, if the value is not found, the else part will get executed , else we can break the loop if the value is present in the sequence.
Let’s see this with the example below. In the below code snippet, there is a list of integers and an item that is to be searched in that list. Using the python for loop, we will be iterating over the list of integers and checking if the item exists or not.
If the item exists, then we print “Item Found” and it comes out of the loop, and the else part doesn’t get executed.
If the item is not present in the list, then the loop completes all the iterations and executes the else block. “Item Not Found.” will be printed in this case.
Output:
The application of using else with the for loop in Python is not limited to this, but there may be many other applications like managing the nested loops, checking limits or boundaries, etc.
Looping through a string in Python
In Python, we can loop through a string. The string is an iterable object containing the sequence of characters. Although Strings are immutable, we can perform operations using the characters to get the desired result.
Let's see the above methods in the below code snippet. There are many ways of iterating through the string in python using a for a loop.
- Method 1: We can iterate over the string character by character until the string gets exhausted. The for loop in each iteration takes one letter from the string and stores it in the variable character, then prints it.
- Method 2: Another way to iterate over the string is using indexing. Since indexing starts at 0, so we can use the range() function which we have seen above. The range() function will take as an argument the stop value, which serves as the end value for the loop.
- Method 3: One more way to iterate over the string is the enumerate() method. The enumerate() takes the string as an argument and returns a key-value pair. Key being the index number by default and value of the corresponding letter in the string. Key can also be other numbers as a counter the starting of which can be passed as an argument.
Output:
Nested Loops in Python
Python allows the use of a loop within the loop. This is known as nesting. For every single iteration of the outer loop, the inner loop executes all its iterations. For instance, if the outer loop has n iterations and the inner loop has m iterations, then the total number of iterations will be n x m. That is for each iteration of the outer loop. The inner loop will execute m times.
Let’s see an example below that makes this more clear. In this, we have two lists named names and city. We want to print each element in the list ‘names’ with all the items in the list ‘city’ concatenated in between with the string ‘loves’ (for example, x loves y). So first, we will be iterating over the list ‘names’ using the for a loop. This will be the outer loop. Now for every iteration of the outer loop, the inner loop will be iterating over the list ‘city’. The total number of iterations, in this case, will be the multiplication of the number of elements in both lists.
Output:
So above, we can see that the total number of times the nested loops are executed is 9. Since n = 3 for the outer loop and m = 3 for the inner loop. So n x m is 3 x 3 = 9.
The break statement
The break is a loop control statement. Using the break statement, we can stop the loop or take out the execution control from the loop before its completion. We stop the further execution of the for loop usually based on some condition(s). Whenever the specified condition is encountered, we use a break statement that takes us out of the python for a loop. However, the break statement can be used without the condition. But with the for loop it is usually accompanied by condition(s) based on the logic of our program when we want to come out from the loop.
Below is the code snippet that shows how it works. The python for loop iterates through a list of integers. In each iteration, an integer is taken into the variable ‘i’ and checked if it is even or not. If the number stored in i is even, then the break statement is executed, and the control comes out of the loop else the odd numbers are printed.
Output:
The pass statement in python
The indentation block of the for loop in python cannot be left blank. Leaving the body of the for loop blank would result in an error. If for some reason, we are required to leave the for loop body blank, then we use a pass statement. By putting the pass statement, we are just telling the loop to execute normally, and controls come out of the loop after all iterations are completed.
Below is the code snippet that can help us understand this better. In the below code, we want to run a for loop in python on the string object ‘name’. But let’s suppose the loop body requires certain functions to be called that we haven’t declared and defined yet. And there must be some order and names defined to call those functions. So while we will be working on the logic of those functions, we can put a pass statement. This will help us in keeping track that we need to add something there as well as if we run our code, then the error would also be avoided.
Output:
The continue statement in python
The continue is a loop control statement. Using the continue statement, we can stop the current iteration of the loop based on some condition(s), and control again comes to the beginning of the loop with the next iteration. Similar to the break statement, it is not necessary for a continue statement too to be accompanied by a condition. The continue statement can be used without condition. But generally, within the for loop in python, we find its condition application to skip some statements in certain iterations.
Let’s see a Python code example below to understand it better. In this, we iterate over a list of different country names and print them. But we want that if the name ‘China’ is encountered, then the name is not printed. For this purpose, we have a condition accompanied by a continue statement that skips the print statement and starts the next iteration of the loop.
Output:
In the above code, you can see that when the value of x is equal to China, the loop didn’t execute fully and control goes back to the next iteration. So this was just a simple case of using a continue statement in Python for loops. We can have many other applications of it depending on the program we are making.
Conclusion
We covered what is for loop in Python, its syntax, and the different ways we can use for loop to iterate over the sequence or series of items. We also saw the internal working of the for loop in python along with the suitable examples. We have also discussed the nested loops and seen the use of else with the for loop in Python. We then covered various loop control statements like a break, continue and pass.