for Loop
The for loop iterate over a sequence.
What is a 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
for value in sequence:
statement(s)
How for loop works?
The variable value holds the element of the sequence on each iteration.
Loop terminates once the last item is iterated in the sequence.
The ‘for’ block starts with the first intended code line and ends with the first unindented line of code.
Example:
for char in 'Python'
print(char)
The below table demonstrates how each iteration works in the above code example
Iteration number |
End of sequence |
Value of variable char |
1 |
No |
'P' |
2 |
No |
'y' |
3 |
No |
't' |
4 |
No |
'h' |
5 |
No |
'o' |
6 |
No |
'n' |
7 |
Yes |
Exit Loop |
Flowchart of for Loop
Flowchart of for Loop in Python
Example: 1
# print welcome to all the names in the list
# List of the names
names = ['Ashish', 'Narayan', 'Mahesh', 'Ramesh']
# iterate over the list
for name in names:
print("Welcome " , name)
Output
Welcome Ashish
Welcome Narayan
Welcome Mahesh
Welcome Ramesh
Example: 2
vowels = ('a', 'e', 'i', 'o','u' )
# iterate over the list
for vowel in vowels:
print("Vowel " , vowel)
Output
Vowel a
Vowel e
Vowel i
Vowel o
Vowel u
Example: 3
# iterate over the range
for val in range(1,11):
print("value is " , val)
Output
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
value is 7
value is 8
value is 9
value is 10
for loop with else
The 'for' loop can have an optional ‘Else’ block. The Else part is executed if the for loop is exhausted
Example: 4
#len function returns the number of elements in the list
for element in range(len(primeno_list)):
print(element)
else:
print("Finished printing list")
Output
0
1
2
3
4
5
6
7
8
9
Finished printing list
Note:
Here, the for loop prints element of the list one by one until the loop exhausts. After for loop exhausts, it executes the else block and prints the Finished printing list
In case a break statement is encountered in the 'for' loop, the else part is ignored.