Python For Loop

The for loop in Python is one of the most commonly used loops. It is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code multiple times.

What is a For Loop?

A for loop is used to iterate over a sequence of items. Each time, the loop takes one element from the sequence and assigns it to the loop variable, which is used inside the loop body.

The syntax of a for loop is:

Syntax of For Loop

Syntax


for variable in sequence:
    # Code block to execute
                

Explanation:

In this syntax:

Example :1


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

for fruit in fruits:
    print(fruit)
                

Output

apple banana cherry
In this example, the for loop iterates over the list fruits. Each time, the loop takes one element (fruit) from the list and prints it.

Using For Loop with Range

The range() function is often used with for loops when you want to iterate over a sequence of numbers. The range() function generates a sequence of numbers starting from the first number to the second number (excluding the second number).

Syntax of Range

Syntax


range(start, stop, step)
                

Explanation:

In the range() function:

Example :2


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

Output

1 2 3 4 5
In this example, the range(1, 6) generates numbers from 1 to 5, and the loop prints each number.

Nested For Loops

It’s also possible to use one for loop inside another, which is known as a "nested for loop". This is helpful when dealing with multi-dimensional data, like lists of lists.

Syntax of Nested For Loops

Syntax


for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # Code block to execute
                

Example :3


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

for row in matrix:
    for element in row:
        print(element)
                

Output

1 2 3 4 5 6 7 8 9
In this example, the outer for loop iterates over each row of the matrix (which is a list of lists), and the inner for loop iterates over the elements of each row.

Best Practices