Python: How to Use 'for' loops

Posted in Python by Dirk - last update: Dec 19, 2023

A for loop in Python is a control flow statement that is used for iterating over a sequence (that is either a list, tuple, dictionary, string, or any other iterable objects). It allows you to execute a block of code multiple times, once for each item in the sequence.

Syntax

The basic syntax of a for loop in Python is as follows:

for variable in sequence:

    # code to be repeated for each item in the sequence

with

  • variable: a variable that takes on the value of the next item in the sequence for each iteration of the loop
  • sequence: This is the iterable object (list, tuple, string, etc.) that you want to iterate over.
  • The indented block of code following the for statement is the body of the loop, and it will be executed for each item in the sequence.

Note: a for loop does not require an indexing variable to set beforehand.

A basic example is:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

Output

1
2
3
4
5

Iterating over a range of numbers

In Python, range(x) represents a sequence of numbers starting from 0 and ending at x-1. It is very useful to use together with the for loop if you have a block of code that you want to execute a specific number of times.


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

This loop will output:

0
1
2
3
4

Iterating over elements of a list

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

This loop will output:

apple
banana
orange

Iterating over characters in a string

A string is an iterable object, it is can be considerd as a sequence of characters. It is possible to loop through the characters.

word = "python"

for char in word:
    print(char)

Output

p
y
t
h
o
n

Iterating over a dictionary

When iterating over items in a dictionary in Python, you typically use a for’ loop along with the items() method of the dictionary. The items() method returns a view object that displays a list of a dictionary’s key-value tuple pairs.

Here’s the basic syntax:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

for key, value in my_dict.items():
    # code to be executed for each key-value pair
    print(key, ":", value)

In this example:

  • key is a variable that will take on the keys of the dictionary one by one.
  • value is a variable that will take on the corresponding values of the dictionary for each iteration.

The items() method returns an iterable view, and the for loop iterates over the key-value pairs, allowing you to access both the keys and values within the loop body.

A more concrete example:

mperson = {"name": "John", "age": 25, "city": "New York"}

for key, value in person.items():
    print(key, ":", value)
name : John
age : 25
city : New York
name : John
age : 25
city : New York

You can use this pattern whenever you need to perform some operation on each key-value pair in a dictionary. It’s particularly useful for tasks like printing, filtering, or transforming the data in some way.

Nested loops

Nested loops in programming refer to the situation where one loop is placed inside another loop. This means that there is an outer loop and an inner loop. The inner loop will be executed for each iteration of the outer loop. This concept is used when you need to perform repetitive tasks within repetitive tasks.

The general structure of nested loops looks like this:

for outer_variable in outer_sequence:
    # Outer loop code
    
    for inner_variable in inner_sequence:
        # Inner loop code

Here’s a simple example using nested for loops to print a multiplication table:

for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end='\t')
    print()

In this example:

  • The outer loop (for i in range(1, 6)) iterates over the values 1 through 5.
  • The inner loop (for j in range(1, 6)) iterates over the values 1 through 5 for each value of i from the outer loop.
  • The print(i * j, end='\t') statement prints the product of i and j with a tab character as the separator (a tab is represented as \t).

The output will be a multiplication table:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

Nested loops are useful when dealing with two-dimensional data structures, such as matrices or grids, or when you need to perform a repetitive operation for combinations of elements from different sets. However, it’s essential to be mindful of the potential increase in complexity and runtime when using nested loops.

Looping over multiple iterables with zip()

The zip() function can be used to iterate over multiple iterables in parallel.

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(name, "is", age, "years old.")

This pairs up elements from names and ages for each iteration of the loop.

Output:

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.

Looping Over Enumerated Iterables:

The enumerate() function can be used to iterate over both the elements and their indices in a sequence.

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

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 apple
1 banana
2 orange

Reversed iteration

The reversed() function allows you to iterate over the elements of a sequence in reverse order.

for i in reversed(range(5)):
    print(i)
4
3
2
1
0

else Clause with for Loop

Similar to while loops, for loops in Python can also have an else clause. The else block is executed when the loop exhausts the items in the iterable (the sequence) or when the loop condition becomes False.

for item in iterable:
    # Loop code

else:
    # Code to be executed if the loop completes without encountering a break statement

Note: if the loop is terminated by a break statement, the else block is skipped.

Exit a loop with break

When the break statement is encountered inside a loop, the loop is immediately terminated, and program control is transferred to the next statement following the loop.

Here’s a basic example:

fruits = ["apple", "banana", "orange", "grape", "kiwi"]

for fruit in fruits:
    if fruit == "orange":
        print("Found the orange!")
        break
    print(fruit)

print("Done!")

In this example, the loop iterates from over the list of fruits. When the fruit matches ‘orange’, the break statement is encountered and the loop is terminated. The output would be:

apple
banana
Found the orange!
Done!

Important: be careful when using break. Break statements can make the code a lot harder to understand. In some cases, restructuring the code to avoid the need for break statements may lead to clearer and more maintainable code.

Skipping Iterations with continue

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration. When the continue statement is encountered, the remaining code inside the loop for that iteration is skipped, and the loop proceeds with the next iteration.

for i in range(5):
    if i == 2:
        continue
    print(i)

In this example, when i is equal to 2, the continue statement is encountered, and the loop skips the print(i) statement for that iteration.

Output:

0
1
3
4

The continue statement is often used when you want to skip certain iterations based on a condition without terminating the entire loop. It can be particularly useful when you want to exclude specific values or handle special cases within the loop.

Here’s another example where the loop skips printing even numbers:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

This loop prints only the odd numbers from 0 to 9:

1
3
5
7
9

Important: as with break, it’s important to use continue carefully, as it can make the code harder to read. In some cases, you can rewrite the code to eliminate the need for continue and achieve the same result in a clearer way.

Other articles