Before we start talking about Python for loop, let's briefly understand-What is for loop ?
The for
loop in Python is used to iterate over sequences or iterable objects. This looping construct allows you to perform repetitive operations on a set of items.
The for and while loops are the two main looping constructs in Python that allow you to repeatedly repeat a block of code.
In this tutorial, we will go over the fundamentals of Python for loops. We'll also show you how to use the range
type to generate a number sequence, as well as break
and continue
statements to change the flow of a loop. We will also address a few FAQs on Python for loop.
Python for
Loop
The for
loop in Python iterates over the items in a sequence and executes a block of statements repeatedly.
The Python for
loop is written as follows:
for item in sequence:
statements
The for
statement begins with the for
keyword, followed by a variable (item
) to which each item of the sequence is assigned (loop control target), the in
keyword, and finally the sequence. Each conditional statement is followed by a colon (:
).
The statements
block begins with an indentation and ends with the first line that is not indented. Most people prefer a 4-space or 2-space indentation. The official Python Code Style Guide recommends using 4-space per indentation level and avoiding mixing tabs and spaces for indentation.
Here is an example:
berries = ["Blueberry", "Raspberry", "Strawberry"]
for berry in berries:
print(berry)
Output
Blueberry
Raspberry
Strawberry
It is possible to iterate over any sequence, such as a string, list, dictionary, or tuple.
We're iterating through the characters in the string 'linux' in the code below:
for x in 'linux':
print(x)
Output
l
i
n
u
x
The variable is assigned to the key when looping through a dictionary:
berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}
for key in berries:
print(key)
Output
Blueberry
Raspberry
Strawberry
Use the key's index to access the dictionary's value:
berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}
for key in berries:
print(berries[key])
The values()
method is another way to loop through the dictionary's values:
berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}
for value in berries.values():
print(value)
The output of both examples is the same:
Output
100
125
150
The range()
Constructor
The Python range()
constructor allows you to generate a sequence of integers by specifying the range's start and end points. In Python 2 and 3, range() behaves differently. Python 3 is used in this tutorial.
range()
is commonly used in conjunction with the for loop
to iterate over a sequence of numbers. This is the Python equivalent of a for loop in C.
When only one argument is provided, range returns a sequence of numbers, each one increasing by one from 0 to argument - 1
:
for i in range(3):
print(i)
Output
0
1
2
When given two arguments, range
returns a sequence of numbers, each one incremented by one, beginning with the first argument and ending with the second argument - 1
:
for i in range(3, 5):
print(i)
Output
3
4
The third argument allows you to specify an increment:
for i in range(0, 16, 5):
print(i)
Output
0
5
10
15
Nested for
Loop
A nested loop is a loop inside another loop. They are frequently used to handle iterable objects that contain iterable elements:
for i in range(0, 6):
for j in range(0, 6):
print('%d + %d = %d' % (i, j, i+j))
Output
0 + 0 = 0
0 + 1 = 1
0 + 2 = 2
...
5 + 3 = 8
5 + 4 = 9
5 + 5 = 10
The break
and continue
Statements
The break
and continue
statements allow you to control how the for
loop is executed.
break
Statement
The break
statement ends the current loop and transfers control to the statement that follows it. The break
statement terminates the innermost loop when used within a nested loop.
In the following example, we use the if statement
to end the loop execution when the current iterated item equals 'Raspberry':
for i in ["Blueberry", "Raspberry", "Strawberry"]:
if i == "Raspberry":
break
print(i)
Output
Blueberry
continue
Statement
The continue
statement exits the current loop iteration and transfers programme control to the next loop iteration. Only the current iteration of the loop is skipped; the loop is not terminated.
We are iterating through a set of numbers in the following example. When the current iterated item equals '3,' the continue statement returns execution to the beginning of the loop and continues with the next iteration:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
4
5
The else
Clause
The for
loop in Python can have an optional else
clause.
When the loop completes normally, i.e. when all iterables are exhausted, the else clause is executed:
for i in ["Blueberry", "Raspberry", "Strawberry"]:
print(i)
else:
print('Loop completed.')
Output
Blueberry
Raspberry
Strawberry
Loop completed.
The else
clause is not executed when the loop is terminated with a break
or continue
statement:
for i in ["Blueberry", "Raspberry", "Strawberry"]:
if i == "Raspberry":
break
print(i)
else:
print('Loop completed.')
Output
Blueberry
FAQs on Python For Loop
How does the for
loop iterate over a sequence?
The for
loop assigns each item in the sequence to the specified variable (item
in the example above) and then executes the code block using that value.
Can you use a for
loop with a range of numbers?
Yes, the range()
function is commonly used with for
loops to iterate over a sequence of numbers. For example: for number in range(1, 5):
Can you iterate over a string using a for
loop?
Yes, a for
loop can iterate over each character in a string. For example: for char in "Hello":
How do you loop through a dictionary using a for
loop?
To loop through a dictionary, you can use the .items()
method. For example: for key, value in my_dict.items():
Can you nest for
loops in Python?
Yes, you can nest for
loops within each other to create nested iterations and traverse multi-dimensional sequences or nested data structures.
How does the break
statement work in a for
loop?
The break
statement is used to exit or terminate the for
loop prematurely. When encountered, it breaks out of the loop, bypassing any remaining iterations.
Can you have an else
block with a for
loop?
Yes, a for
loop can have an optional else
block that executes once the loop has completed iterating over the sequence, unless the loop was terminated by a break
statement.
Conclusion
The Python for
loop is used to execute a block of code for a set number of times.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.