Loops are the way of performing repetitive tasks efficiently.
For example, you need to add 10 to each of the values present in the list [ 10,20,30,40 ]. Hence we go through each of these values one by one and perform the addition, this is looping.
In the below code, a temporary variable ‘i’ is chosen as the iterator. the value of ‘i’ changes four times in the below code, as there are four values in the list, hence, in the first round the value of ‘i’ will be 10, in the next round it will be 20 so on and so forth.
instead of the variable name ‘i’, you can choose any other valid python variable name like my_iterator, list_iterator, myValue etc.
|
1 2 3 4 5 6 |
# Creating a sample list sampleList=[10,20,30,40] # For loop for i in sampleList: print(i+10) |
Sample Output:

Looping with multiple iterators
Python has a facility to loop multiple iterators simultaneously. The keyword to be used in zip.
|
1 2 3 4 5 6 7 |
# Creating sample objects sampleList=[10,20,30,40] sampleTuple=['a','b','c','d'] # Looping two objects at a time for numIterator, charIterator in zip(sampleList, sampleTuple): print(numIterator, '--', charIterator) |
Sample Output:

Nested for Looping
You can run a sub loop inside a loop as well. Here, each value of the outer loop object will be used once with each value of the inner loop object.
|
1 2 3 4 5 6 7 8 |
# Creating sample objects sampleList=[10,20,30,40] sampleTuple=['a','b','c','d'] # Nested for loop for multiple iterators for numIterator in sampleList: for charIterator in sampleTuple: print(numIterator, '--', charIterator) |
Sample Output:


Wow!