The Python for Loop

Introduction

A loop is a way for a programming language to repeat a block of code multiple times. Doing the exact same thing repeatedly is not often useful and rather boring, that’s why loops often use a different value for a variable in each repetition. The Python for loop does that by assigning the variable from an iterable object, (such as a list or tuple). The iterable object, which implements a standard Python protocol for returning items in a sequence, is called by the for loop behind the scenes, to return the next item in each iteration.

Basic Python for Loop Syntax

The Python for loop syntax consists of the for keyword, a variable that represents the current element in the iterable sequence, the in keyword, and the iterable object itself, followed by a colon :. The code block, which is indented below the for statement, is executed for each element in the sequence.

Indentation is crucial for the correct execution of the code within the for loop. Python relies on indentation to determine the scope of code blocks.

Here’s the syntax of the basic for loop:

for element in iterable:
    loop-block
  • element: The variable that represents the current item in the sequence. The for loop assigns this variable one item from the iterable at each repetition of the loop.
  • iterable: The iterable over which the loop iterates.
  • loop-block: The code that will execute for each element in the sequence. This code block is also called the body of the loop.

Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

In the example above, the for loop iterates over the list of fruits, and the print statement inside the loop block is executed for each item, resulting in the output of each fruit on a new line.

The range() Function

The range() function is often used in conjunction with for loops to generate a sequence of numbers. It takes up to three arguments start, stop, and step and creates an iterable that returns the integers from start up to stop (non-inclusive), skipping step each time.

A for loop can conveniently iterate over the numbers generated by range().

Here’s the syntax using the range() function with a for loop:

for i in range(start, stop, step):
    loop-block
  • i: The variable that represents the current number in the sequence.
  • start: The starting value of the sequence (default to 0).
  • stop: The end value of the sequence. The stop point is non-inclusive, meaning the sequence with go up to but not include the value of stop.
  • step: The step or increment between numbers (default to 1).

Example:

for i in range(1, 5):
    print(i)

Output:

1
2
3
4

In the example above, the for loop iterates over the numbers generated by range(1, 5), and the print statement inside the loop block is executed for each number.

Example:

for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9

The above example uses the step parameter to step by 2 and print only the odd numbers from 1 to 9.

Example:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

The final range() example above demonstrates utilizing the default value of 0 for start. The result is a printout of a sequence of 5 numbers that starts with 0 and ends with 4.

Nested for Loops

You can also nest for loops within each other to create more complex iteration patterns, especially useful when working with nested data structures.

Example:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()

Output:

1 2 3 
4 5 6 
7 8 9 

In the example above, the outer for loop iterates over each row of a matrix, and the inner for loop iterates over each element in the row, printing the matrix in a readable format. Note that in the inner for, the iterator is the loop variable row of the outer for.

Summary & Reference for the Python for Loop

The Python for loop is a construct for executing a block of code repeatedly for each item in an iterable.


Its basic syntax uses the for keyword, a variable representing the current element, the in keyword, and the iterable object followed by a colon :.

for element in sequence:
    loop-block

Here is an example that prints items in a list using a for loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

The range() function is commonly used with for loops to generate a sequence of numbers. It takes start, stop, and step arguments, allowing for flexible iteration over numeric ranges.

for i in range(start, stop, step):
    loop-block

Nested for loops enable the iteration over complex data structures, such as matrices or nested lists, providing a way to traverse multiple levels of elements.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()