For in Loop in Python
Loop is used to iterate the elements of a sequence. for Loop is used to display all elements of any sequence. sequence This is a list, tuple, dictionary and string.Syntax for for_in Loop
for variable in sequencefor_statement (s)
When iteration starts, an element of sequence is assigned to the variable and the given statement is executed. The iteration continues till that number of elements is there and after that the control of the loop comes out of the loop.
Example for Iterating list sequence
Iterating list sequence |
Source Code:
a = [3, 1, 23, 5, 12, 2]
for n in a:
print (n)
Output:
31
23
5
12
2
Example for Iterating tuple sequence
Iterating tuple sequence |
Source Code:
tuple = (1, 2, [3, 4, 5], 6, 7, 8)
for a in tuple:
print (a)
Output:
12
[3, 4, 5]
6
[7, 8]
Example for Iterating dictionary sequence
Iterating dictionary sequence |
Source Code:
dic = {1: 6, 2: 5, 3: 3, 4: 8, 5: 4, 6: 2, 7: 5, 8: 4, 9:11, 12:45}
for a in dict:
print (a, dict [a])
Output:
1 62 5
3 3
4 8
5 4
6 2
7 5
8 4
9 11
12 45
Example for Iterating string sequence
Iterating string sequence |
Source Code:
str = "Hello World"
for a in str:
print (a)
Output:
H
e
l
l
o
W
o
r
l
d
else with for Loop
When the iteration of the elements of a sequence in the for loop is over, then the else statement; will executeelse with for Loop |
Source Code:
name = ['priti ', 'Sidhi', 'Gurinder']
for i in name:
print (i)
else:
print ("Outside of for Loop")
Output:
priti
Sidhi
Gurinder
Outside of for loop
0 Comments