Python for Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
n=[1,2,3,4,5,6,7,8,9,10] for i in n: print(i)
Output:
1
2
3
4
5
6
7
8
9
10
>>>
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.
Hence, a for loop’s else part runs if no break occurs.
n=[1,2,3,4,5] for i in n: print(i) else: print("List complete")
Output:
1
2
3
4
5
List complete
>>>
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints
List complete
Examples:
For loop with list
Example:1
Write a python script to display elements stored in a list
Sol:
n=[1,2,3,4,5,6,7,8,9,10] for i in n: print("number is ",i)
Output:
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
number is 7
number is 8
number is 9
number is 10
>>>
Example:2
print all the elements of the list along with their square.
Sol:
n=[1,2,3,4,5,6,7,8,9,10] for i in n: print(i," ",i*i)
Output:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
>>>
Example:3
Write a python script to print all the elements of the list along with their square and cube.
Sol:
n=[1,2,3,4,5,6,7,8,9,10] for i in n: print(i," ",i*i," ",i*i*i)
Output:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>>
Example:4
Write a python script to display elements stored in a list and also calculate and print their sum.
Sol:
n=[1,2,3,4,5] s=0 for i in n: print(i) s=s+i; print("Sum = ",s)
Output:
1
2
3
4
5
Sum = 15
>>>
Example:5
Write a python script to display all the elements stored in the list and also print the count of all the elements.
Sol:
n=[23,4,56,7,68,4] c=0; for i in n: c=c+1 print(i) print("Total elements in the list = ",c)
Output:
23
4
56
7
68
4
Total elements in the list = 6
>>>