Loops are one of the essential elements in any programming language, and Python is not an exception to it. Loops are used to repeat a statement or a block of statements multiple times. If there were no concept of loops in programming languages, we have to write each statement again and again for the number of times we want to execute it.
Python provides two types of loops to handle looping requirements, i.e., the while loop and the for loop. In this tutorial, we will learn everything about the for loop statement in Python.
Before getting started with this tutorial, It is necessary to have Python installed and set up in your environment path. If you don’t have it installed already, refer to our step by step guide to install Python on Linux. The code presented in this tutorial can be run on the python shell, but it is recommended to run the code in a Python IDE. If you don’t have a python IDE installed in your system or want to know which IDE is a better choice to install, you can refer to our guide Top 10 best python IDE compared.
Python For Loop Overview
The for loop in Python can iterate over items of any sequence, including a string, list, tuple or dictionary. The basic syntax of the for loop in Python is :
for var in sequence:
statement(s)
Here, a sequence is a collection of objects—for example, a list or tuple. The var in the syntax is the loop variable, and it takes the next element of the sequence whenever the loop body executes.
This is less like the for keyword present in other programming languages and works more like an iterator method, as found in other object-orientated programming languages. If you have ever used programming languages like C or C++ you may have seen the syntax of for loop similar to the syntax below:
for(initialization; condition ; increment/decrement)
{
statement(s);
}
This syntax of for loop is also used by many other programming languages like Java, PHP, etc. The Python for loop syntax is most like the natural language, so its easy to read and use.
Iterating through a String
Strings are beneficial data types in Python, and we can quickly iterate over strings using the Python’s for loop. See the below example for illustration. The following code can be run in the python shell.
for i in "python"
print(i)
This code will iterate over the string python and print each letter present in the word as output. The output of the program will look like the below image.
Using a for loop through the string is very useful in any situation. For a practical example, we can count the number of letters present in a string using the for loop. See the below example to see the illustration. However, there is a built-in len() function in Python to count the length of strings, list, tuples, etc. The below program is just an illustration of how to do it manually. Copy the following code into a python file name it length.py and run it by typing the command python length.py in your terminal.
count = 0
for i in "python":
count = count + 1
print("The number of letters is :",count)
This simple program can be used to count the number of words present in a string. The output of the above code will look something like in the following image.
Let’s see what is going in the above code. In the first line, we initialize the count variable with the value 0. In the second line, the loop iterates the i variable over the letters of the “python” string, and for every iteration, there will be an increment in the count variable.
Looping through a Python List
We can also use the Python for loop in a python list. Python list is one of the most popular data structure used in Python, thus a way to iterate it is handy for programmers. The looping of a python list is almost similar to the looping of a string. See the following python code for an illustration, copy the code into the python IDE, and run it.
programming_lang = ["python", "java", "rust", "golang", "c", "swift"]
for languages in programming_lang:
print(languages)
In the first line, we initialize a variable named programming_lang with a list. In the next line, we iterate through that python list using a variable language and print the elements of the list one by one. The output of the program seems as in the following image.
Let us see a practical example to know how this concept will help us in programming. In the following program, we will calculate the sum of all the numbers present in a python list.
numbers = [1,4,7,2,9,10,55]
i = 0
j = 0
for i in numbers:
i = i + j
j = i
print("The sum of the elements in list is",j)
The above program will print the sum of all the elements present in the list, as shown in the below image.
Looping through a Python Dictionary
We have seen earlier how to use the for loop in python lists and strings. Now we are going to see how to use the for loop in python dictionary which is also an exciting and powerful data structure in Python.
Lets, see how to use for loop over the Python’s dictionary. Simply copy the following code into a python file and run it.
fruits_quantity = {"apple":10, "mango":5, "banana":15}
for fruit in fruits_quantity:
print("The quantity of " + fruit + " is :", fruits_quantity[fruit])
When we run the above code, we may see the output something similar to the following image.
Let’s see what is happening in the above code, In the first line, we create a python dictionary named fruits_quantity and store some fruit names as dictionary keys and the number of fruits as the dictionary data. When we perform the for loop operation using a loop variable fruit, it iterates over the keys of the dictionary. Due to this, we can access a single key from the dictionary in one execution of the loop body, and by accessing the key, we can also access the data that the key hold.
The range() Function
The built-in range() function in Python is the right function to iterate over a sequence of numbers. The syntax of range function is
range(n)
The range() function generates an iterator to progress starting from 0 up to (n-1). By default, the starting point is 0, but you can also enter a custom starting point. see the following code for illustration
range(2,5)
This code will generate the sequence of numbers from 2 to 5. The output will be
>>> range(2,5) range(2, 5)
You can also typecast the range() function into a list by using the list function. See the following code as an example. Type the following code into the python shell.
list(range(5))
On running the above code, you will see the output as shown below. The code will produce a python list with a sequence of numbers ranging from 0 to 4.
>>> list(range(5)) [0, 1, 2, 3, 4]
Now, let us see how we can use the power of range() function with the Python’s for loop and what is its necessity. The for loop has no builtin method to iterate over numbers in Python as there are in other programming languages, this requirement is fulfilled by the range() function. See the following code to know the working of the range() function with the for loop.
for i in range(10):
print(i)
The above program iterates over the range function and displays the numbers from 0 to 9. The output looks like the following image.
You can also display the elements of a list, string, tuple or dictionary using the range() function with the for loop. See the following illustration to see how it works.
fruits = ["apple","mango","grapes","pineapple"]
for i in range(2):
print(fruits[i])
The output of the program is shown in the below image.
If the argument of the range() function is higher than the number of elements present in the list, you will get an IndexError.
Loop Control Statements
The loop control statements alter the execution of the loop from its typical sequence. Python supports three types of loop control statements; they are the break, continue, and pass statement. Let’s see details about how to use them.
The break statement
The break statement is one of the most used loop control statements. With the help of the loop statement, we can terminate the loop before it has looped through all the items. The execution is transferred to the next statement following the loop. The most common use of break is when some external condition is triggered, requiring a sudden exit from a loop. The break can be used in both while, and for loops, It is like the traditional loop present in C programming language. For illustration, see the following code, Copy the below code into your python IDE and run it.
fruits = ["apple","mango","grapes","pineapple"]
for fruit in fruits:
if fruit =="grapes":
break
print(fruit)
print("Exited from the loop")
In the above program, the loop will be terminated when the element of the list is grapes. After termination of the loop, the execution is followed by the next statement present after the loop. In our code, it is a print statement, as shown in the output image below.
The continue statement
The continue statement in Python is almost similar to the break statement. Still, instead of terminating the whole loop, it only terminates the current iteration and proceeds to the next iteration. For illustration, see the below example. Copy the code into your favorite IDE and run it.
fruits = ["apple","mango","grapes","pineapple"]
for fruit in fruits:
if fruit =="grapes":
continue
print(fruit)
The above code will skip the iteration for the string “grapes” present in the list, so it is not displayed in the output of the program. The output is shown in the below image.
The pass statement
The pass statement is used when a statement is needed syntactically, but we don’t want any code to execute. Since for loops cannot be kept empty if, for some reason, we want to keep it empty or want to write the loop statements, later on, we can use the pass statement in the loop body loop. Run the following python code.
for i in "python":
By running the code, you will get an error. The error may seem like this.
SyntaxError: unexpected EOF while parsing
To prevent this error for an empty for loop. We can give a pass statement in the loop body. On running the following code, we will not get any error, and the requirement of an empty loop will also fulfill.
for i in "python":
pass
The above code runs smoothly, without any error. Although the pass is not as popular as the break and continues statements in some cases, it may be useful.
The else clause in for loop
We can also use the else clause in a for loop. The statements or blocks present inside the else clause will execute after the iteration of the for loop executes completely. See the following code for an illustration on the use of else clause with for loop.
for i in range(10):
print(i)
else:
print("Displayed")
The above code will first execute the loop and print a sequence of numbers from 0 to 9. Then it will display the message “Displayed” into the screen, as shown in the below image.
If the for loop terminates before complete execution due to a break statement or any other reason, then the statement(s) under the else clause will not execute. See the below example for an illustration.
for i in range(10):
print(i)
if i == 6:
break
else:
print(" Displayed Successful ")
In this example, only a sequence of numbers from 0 to 6 will be displayed. The print statement inside the else clause will not execute as the break statement terminates the loop before the complete iteration. See the following for the output of the above program.
Nested for loops
Like any of the popular programming languages, Python also supports the use of nested loops. Nested loops are one loop present inside another loop. This is a handy concept of loops in a programming language. In a nested loop the “inner loop” will be executed one time for each iteration of the “outer loop”. The syntax of the nested loop is shown below.
for var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
For practical use of nested loops, see the below example program.
for i in range(1,6):
for j in range(1,11):
print(i*j, end=" ")
print("\n")
The above code will print the multiplication table of 1 to 5. You will see the output of the program, as shown in the below image.
We can put any type of loop inside any other kind of loop. For example, a for loop can be inside a while loop or vice versa.
Conclusion
That’s all about the usage of Python for loop. As you can see, the usage of for loops is highly efficient when a set of statements are to be executed iteratively over a sequence of elements. You may also want to see working with the operating system using Python.