Python: For Loop


Python provides a for loop to iterate over a sequence (e.g. a list, tuple and dictionary). This is a convenient tool when you want to traverse all or a few
elements of a sequence without worrying about the number of elements in the sequence.

arr = [1, 3, 2, 6, 90, 34, 5]

for elem in arr:
     print (elem)

The output of this snippet will print each element of the list in a new line.

For Loop: Break keyword

There are situations where we want to terminate our loop even if all the elements are not yet traversed, e.g. when finding a desired value and you saw it in the middle of the sequence. In such cases, you would want to terminate the loop. Python provides the break keyword for this scenario.

arr = [1, 3, 2, 6, 67, 23, 45]
for elem in arr:
   if elem == 6:
      break        # loop will be terminated as it encounters 6

For Loop: Continue keyword

Situations where we want to skip only the current iteration of the loop. Python provides a continue keyword for such a scenario.

arr = [1, 3, 2, 6, 67, 23, 45, 49]
for elem in arr:
   if elem % 2 == 0:
      continue        # Loop will skip from here to next iteration
   print (elem)