Loops in Python: For Loop

Loops are used when one wants to repeat a set of statements several times (iterations). For example, when you want to apply a set of operations on elements of a list, by choosing one element at a time, you can use a python loop.

There are two types of loops:

  • For loop
  • While loop

For loop: 

For loop is used when we want to run the set of commands for a known or defined number of times. Few of the ways in which we can use the “for loop” is as follows:

Python





for i in range(10):
    print(i)
range(start, stop, step)

Here the range(10) function will create number in sequence starting from 0 and ending at 9. The value of i will thus stat from 0 and increase by 1 in each iteration stopping at 9

The general format of range function is:

Python





range(start, stop, step)

By default the value of step is 1. 

The other way of running for loop is:

Python





mylist = ["a", "b", "c"]
for i in mylist:
    print(i)
    
mylist = ["a", "b", "c"]
for i, element in enumerate(mylist):
    print(f'index: {i}, element: {element}')




a
b
c

Here, the for loop iterates over each element in the list (mylist). In the first loop the value of “i” is “a”; in the second loop the “i” has the value of “b”; and so on.

The enumerate function allows us to simultaneously iterate over the elements of a list as well as yielding the indices of the current element in the list in a particular iteration.

Python





mylist = ["a", "b", "c"]
for i, element in enumerate(mylist):
    print(f'index: {i}, element: {element}')




index: 0, element: a
index: 1, element: b
index: 2, element: c

This is useful when you might need to access the elements of other lists relative to this index in the loop.