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, we will learn about Python for loop and explore different ways to perform iterations using the same in Python.
For Loop in Python
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.
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
numbers = [1, 2, 3, 4, 5] for x in numbers: print(x*x) #outputs 1 4 9 16 25
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 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
>>> 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 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
>>> 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
>>> l=[(1, 1), (2, 8), (3, 27)] >>> for (x, y) in l: ... print(y) 1 8 27
Like other programming languages, Python for loop iterates through the items of a sequence and executes the statements the same numberof times.