for loop in python is used to iterate over a sequence like list, tuple, dictionary, set or string etc and run a block of code with each element of collection. If we want to execute a block of code repeatedly then we use for loop.
General Syntax:
for loop begins with a header line that specifies an assignment target, along with the object you want to step through.
for val in sequence:
Body of for loop
else:
body of else part
when for loop runs, it assign the items from sequence to target value one by one and execute loop body for each.
Now let’s take a real example:
IntList=[0,1,2,3,4,5,6,7]
for x in IntList:
print(x)
In above example we have a list of integers and we are printing all elements one by one through for loop.
Use ‘for’ keyword and then a variable to hold value of elements in every iteration and ‘in’ key word to define which sequence is to be used then start the body of loop. Loop continues until we reach the last element of sequence.
The range() function:
we can generate sequence of number through range() function like range(5) mean a sequence of number through 0 to 4.
we can adjust the range function by specifying the start and end limit and step size. for example
print(range(5))
#Output
#range(0, 5)# To print the range use list
print(list(range(5)))
#Output
#[0, 1, 2, 3, 4]#Specify custom range
print(list(range(2,8)))
#[2, 3, 4, 5, 6, 7]
- to display whole range use list(range)
- for custom range use range(LowerLimit,UpperLimit) as explains in above code.
we can use this range function with for loop to display elements of range one by one.
for x in range(5):
print(x)#output
0
1
2
3
4
we can use len() function in range to define the range of any sequence like
Names=["umar","john","David"]
for x in range(len(Names)):
print(x)
#output
0
1
2
use of break kay word in for loop:
break key word breaks the loop i.e. when break key word is encounters in loop body then all next iterations will be skip out. Look at following example first then we will explain.
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
if(x==3):
break
else:
print(x)
#output
0
1
2
we have put if condition in loop so, when x become 3 condition become true and break statement is executed and next iteration is skipped.
Use of continue in for loop:
if we want to skip a specific iteration in sequence then we can use continue statement like.
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
if(x==3):
continue
else:
print(x)
#output
0
1
2
4
5
6
7
in above code only 3 is not print out because we have put condition on 3, as x become 3 then current iteration is skip out and continue with next iterations.
else in for loop:
else part of for loop only executes when loop terminates i.e. when condition become false. if loop terminates with break statement then else part will not executed. For example.
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
print(x)
else:
print("Loop finished")#output
0
1
2
3
4
5
6
7
Loop finished
if we use break to terminate the loop then else part will not executes.
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
if(x==2):
break
print(x)else:
print("Loop finished")#output
0
1
Look at above code else part has not executed.
python Nested for loop:
Nested loop mean loop inside a loop. we can nest loops as many time as we want. Inner loop will executes one time for every iteration of outer loop. For example
Row=[0,1,2,3,4]
col=[5,6,7,8,9]
for x in Row:
for y in col:
print(x,y)
else:
print("Loop finished")#output
0 5
0 6
0 7
0 8
0 9
1 5
1 6
1 7
1 8
1 9
2 5
2 6
2 7
2 8
2 9
3 5
3 6
3 7
3 8
3 9
4 5
4 6
4 7
4 8
4 9
Tuple assignment in for loop:
- iterate over a tuple.
MyTuple=("I","am","studying","python")
for x in MyTuple:
print(x)
- if we are iterating through a sequence of tuple(a sequence whose all elements are tuple) then target value becomes a tuple because sequence on which which we are iterating contains tuples as elements so for each iteration one elements i.e. a tuple will be assigned to target value. For example, create a list of tuples and print it.
MyList=[(0,1),(1,2),(3,4),(5,9)]
for x in MyList:
print(x)#output
(0, 1)
(1, 2)
(3, 4)
(5, 9)
Look at the output of above example every time a tuple will be printout.
- tuples with for loop also helpful to iterate through both keys and values in dictionaries using items method, rather than looping through keys and indexing to fetch values manually. you can read detail about dictionary here.
Frist fetch value through manual indexing.
MyDict={'a':1,'b':2,'c':3,'d':4}
for keys in MyDict:
print(keys,MyDict[keys])#output
a 1
b 2
c 3
d 4
Now use tuple and items() method.
MyDict={'a':1,'b':2,'c':3,'d':4}
for (key,value) in MyDict.items():
print(key,value)#output
a 1
b 2
c 3
d 4
python for loop examples:
- compute the sum of all elements in a list using for loop.
IntCollection=[0,1,2,3,4,5,6,7]
sum=0
for x in IntCollection:
sum=sum+x
print(sum) #28
- print alphabets of a string using for loop.
MyStr="Artificial"
for x in MyStr:
print(x,end=' ')#A r t i f i c i a l