How the for loop works in Python

Overview

In any programming language, the for loop is used to traverse the given object in a sequential manner.

In Python, the for loop is not like that of other programming languages. It behaves like an iterator method and the difference has been illustrated in one of the examples below. The body of the loop is differentiated from the remaining code by indentation.

Syntax

for iterator_var in sequence:
    loop_statements

Flow diagram

How to iterate specific times

To iterate over a sequence some specific times, we use the range() function, which gives a sequence with a default starting value of 0. It increments by 1 unless the step size is modified, and ends at the number specified in the arguments.

Suppose the arguments are range(2,14,2). The values would be 2,4,6,8,10,12. Below is an example:

for i in range(2,14,2):
print(i)

Explanation

  • Line 1: We run the for loop with the starting index value, 2, and ending value, 14, of 2 increments every iteration.
  • Line 2: We print the x value.

How to iterate over a string

Strings can also be used as iterable objects in Python in a for loop. Below is an example:

for n in range(7):
print("value on n is {}" .format(n), end='\n')

Explanation

  • Line 1: We run the for loop with 0-7 range with 1 increment every iteration.
  • Line 2: We print the n value with the string.

How to iterate over a list

We can also iterate over elements of a list. Below is an example:

breakfast = ["cereal", "bread", "yogurt"]
for x in breakfast:
print(x)

Explanation

  • Line 1: We create a list with the name, breakfast.
  • Line 2: We iterate the for loop on the list.
  • Line 3: We print the x value.

Iterator and Iterable

Iteration over the sequence in Python involves two types:

  • IterableThe object the loop is iterating over
  • IteratorThe object that does the actual iteration; it fetches the next item in the sequence

Thus, n = 7 will not stop our loop in the code below.

for n in range(7):
print("value on n is {}" .format(n), end='\n')
n = 7

Explanation

  • Line 1: We run the for loop with 0-7 range with 1 increment every iteration.
  • Line 2: We print the n value with string.
  • Line 3: We assign the value, n = 7.

Similarly, for loops can be used to iterate over a tuple, a dictionary, or even a set.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved