Aim of ‘for’ loop is same as that of while loop. However, for loop is used to iterate over a particular sequence or order. This loop can iterate over string, list, tuple, range and many more.
for variable in sequence: Statements
Let’s understand the working of for loop with the help of an example :
Program : To display counting from 1 to 10.
for i in range(1,11): print(i,end=' ')
1 2 3 4 5 6 7 8 9 10
Accessing list elements using for loop :
lst=[3,4,5,6,7] for i in lst: print(i,end=' ')
3 4 5 6 7
Here, variable i is acting as a list element.
We can write above code as :
lst=[3,4,5,6,7] for i in range(0,len(lst)): print(lst[i],end=' ')
Here, element is accessible by last[i].