Like other programming languages, Python also has a ‘for’ iterative statement (also known as ‘for loop’) to execute a set of codes for a definite or indefinite number of times.
In this tutorial, you will learn about for loop in Python and in addition will also learn different ways to perform iterations using the for statement.
For Loop in Python
The for
statement (also known as for loop) is an iterator in Python that iterates over the items of any given sequence or collection of objects (also known as iterable) in the order they appear.
The sequence could be a Python string, list, dictionary, a range of numbers, etc.
The for
statement in Python is written like the following:
for <item> in <sequence>:
<statements>
The statements written in the body of the for
loop are executed for every item in the given sequence.
Like in the following code, the print
statement executes for every item in the given list:
numbers = [1, 2, 3, 4, 5]
for x in numbers:
print(x*x)
#outputs 1 4 9 16 25
The for
loop executes the statements in its body multiple times depending on the number of items in the sequence.
Let’s look at some examples to find out how to use the ‘for’ loop in Python to perform various tasks.
Examples using for loop
Example 1: Display the same string multiples times using the for
loop
>>> for element in range(0, 5):
... print("pencil programmer")
pencil programmer
pencil programmer
pencil programmer
pencil programmer
pencil programmer
Example 2: Check for even and odd numbers in the list using the for
statement.
>>> l = [1, 2, 3, 4]
>>> for integer in l:
... if integer%2==0:
... print(integer," :even number")
... else:
... print(integer," :odd number")
1 :odd number
2 :even number
3 :odd number
4 :even number
Example 3: Print only odd numbers in the given range using for
loop.
>>> for x in range(0, 10):
... if x%2!=0:
... print(x, end=' ')
1 3 5 7 9
Example 4: Find sum of first 10 non-negative integers using for
loop.
>>> sum=0
>>> for integer in range(0,10):
... sum=sum+integer
>>> print(sum)
45
Example 5: Iterate through the characters of a string.
>>> string='pencil programmer'
>>> for x in string:
... print(x, end=' ')
p e n c i l p r o g r a m m e r
Example 6: Iterate through a list of tuples using for
loop.
>>> l=[(1, 1), (2, 8), (3, 27)]
>>> for (x, y) in l:
... print(y)
1
8
27
Similar to other programming languages like C or Java, for
statement in Python is used to iterate through the sequence of items and executes the same set of statements for each item in the given sequence.