For Loop
For Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Syntax:
Body of for
Here, element is the variable that takes the value of the item inside the sequence on each iteration.
Flow Chart
Example
In [2]:
#Find product of all numbers present in a list
product = 1
#iterating over the list
for ele in lst:
print(type(ele))
product *= ele
<class 'int'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'int'>
Product is: 12200000.0
In [3]:
ele
Out [3]: 50
range() function
We can generate a sequence of numbers using range() function. range(10) will generate numbers from
0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if
not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers the start,
stop, step size and generates the next number on the go.
In [4]:
#print range of 10
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
In [5]:
#print range of numbers from 1 to 20 with step size of 2
for i in range(1, 20, 5):
print(i)
1
6
11
16
In [6]:
lst = ["satish", "srinu", "murali", "naveen", "bramha"]
satish
srinu
murali
naveen
bramha
In [9]:
lst = ["satish", "srinu", "murali", "naveen", "bramha"]
for i in range(len(lst)):
print(lst[i])
satish
srinu
murali
naveen
bramha
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
In [10]:
numbers = [1, 2, 3]
1
2
3
no item left in the list
In [11]:
for item in numbers:
print(item)
if item % 2 == 0:
break
else:
print("no item left in the list")
1
2