Iterations and Loops

Imagine that you need to repeat some action many times. For example, greeting each guest at a party or counting all items in a list. Doing this manually would be tedious. And this is where loops come to the rescue! 🔄

Loops help automate repetitive actions, allowing you to execute the same block of code multiple times. This saves time and makes your code cleaner and more efficient.

What are iterations and loops?

An iteration is a single execution of a set of instructions. And a loop is a construct that allows a block of code to be executed multiple times while a certain condition is met.

Python offers two main types of loops:

  • The for loop: used to iterate over a sequence (list, tuple, string, etc.)
  • The while loop: executes as long as the specified condition remains true

The for loop

The for loop is used to iterate through elements of a sequence (list, tuple, string, etc.). This is the most common type of loop in Python.

For loop syntax

The basic syntax of a for loop looks like this:

Python 3.13
# Simple example of a for loop
>>> fruits = ["apple", "banana", "cherry"]

>>> for fruit in fruits:
...     print(f"I love {fruit}!")
I love apple!
I love banana!
I love cherry!

In this example:

  1. fruit is the iterator variable that takes the value of each element in the fruits list in turn
  2. The loop body executes for each element in the list
  3. After : follows an indented code block that is executed in each iteration

Iterating over a range of numbers

Often we need to execute a loop a certain number of times. For this, the range() function is used:

Python 3.13
# Using range() to create a sequence of numbers
>>> for i in range(5):  # from 0 to 4
...     print(f"Number: {i}")
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

The range() function creates a sequence of numbers and has several usage options:

Python 3.13
# Range() usage options

# range(stop): from 0 to stop-1
>>> for i in range(3):
...     print(i, end=" ")
... print()  # For line break
0 1 2
# range(start, stop): from start to stop-1 >>> for i in range(2, 5): ... print(i, end=" ") ... print()
2 3 4
# range(start, stop, step): from start to stop-1 with step >>> for i in range(1, 10, 2): # Odd numbers from 1 to 9 ... print(i, end=" ")
1 3 5 7 9

Iterating over strings

Strings in Python are also sequences, so we can iterate through their characters:

Python 3.13
# Iterating through characters in a string
>>> message = "Python"

>>> for char in message:
...     print(char)
P
y
t
h
o
n

Iterating with indices

Sometimes we need both elements and their indices. For this, the enumerate() function is used:

Python 3.13
# Getting indices and values
>>> fruits = ["apple", "banana", "cherry"]

>>> for index, fruit in enumerate(fruits):
...     print(f"Index {index}: {fruit}")
Index 0: apple
Index 1: banana
Index 2: cherry

The while loop

The while loop executes as long as the specified condition remains true. This is useful when we don't know in advance how many times the loop should execute.

While loop syntax

Python 3.13
# Simple example of a while loop
>>> count = 1

>>> while count <= 5:
...     print(f"Loop is executing for the {count}th time")
...     count += 1  # Increasing the counter
Loop is executing for the 1th time
Loop is executing for the 2th time
Loop is executing for the 3th time
Loop is executing for the 4th time
Loop is executing for the 5th time

In this example:

  1. The loop executes while count <= 5
  2. Inside the loop, we increase count by 1 in each iteration
  3. When count becomes 6, the condition becomes false, and the loop terminates

Important: In a while loop, you always need to change the variable involved in the condition, otherwise the loop may become infinite!

Infinite loop

If the condition in a while loop is always true, the loop will execute infinitely. This can be useful, but usually requires a way to exit such a loop:

Python 3.13
# Example with explicit breaking of an infinite loop
>>> counter = 0

>>> while True:  # This condition is always true
...     print(f"Iteration {counter}")
...     counter += 1

>>>     if counter >= 5:  # Condition to exit the loop
...         print("Exiting the loop!")
...         break  # Interrupts the loop execution
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Exiting the loop!

Loop control

Python provides several tools for controlling loop execution.

The break statement

The break statement allows you to immediately exit a loop, regardless of the condition:

Python 3.13
# Using break to exit a loop
>>> for i in range(10):
...     print(i, end=" ")
...     if i == 5:
...         print("\nReached number 5, exiting the loop!")
...         break
0 1 2 3 4 5
Reached number 5, exiting the loop!

The continue statement

The continue statement skips the current iteration and moves to the next one:

Python 3.13
# Using continue to skip iterations
>>> for i in range(10):
...     # Skip even numbers
...     if i % 2 == 0:
...         continue
...     print(i, end=" ")
1 3 5 7 9

The else block in loops

for and while loops can have an else block that executes when the loop terminates normally (not through break):

Python 3.13
# Using else with a loop
>>> for i in range(5):
...     print(i, end=" ")
... else:
...     print("\nLoop completed normally")
0 1 2 3 4
Loop completed normally
# Example with break - the else block won't execute >>> for i in range(5): ... print(i, end=" ") ... if i == 2: ... break ... else: ... print("\nThis line won't be output because the loop was interrupted")
0 1 2

Nested loops

Loops can be nested inside each other to process multidimensional data structures or solve more complex problems:

Python 3.13
# Example of nested loops - multiplication table
>>> for i in range(1, 4):  # Rows
...     for j in range(1, 4):  # Columns
...         print(f"{i} × {j} = {i*j}", end="\t")
...     print()  # Moving to a new line after each row of the table
1 × 1 = 1 1 × 2 = 2 1 × 3 = 3
2 × 1 = 2 2 × 2 = 4 2 × 3 = 6
3 × 1 = 3 3 × 2 = 6 3 × 3 = 9

Tip: Nested loops can be resource-intensive, especially with a large number of iterations. Use them carefully and look for more efficient alternatives for processing large volumes of data.

List Comprehensions

List comprehensions are an elegant way to create lists in one line using syntax similar to a for loop:

Python 3.13
# Creating a list of squares of numbers from 0 to 9
# Regular way
>>> squares = []
>>> for i in range(10):
...     squares.append(i**2)
... print(f"Regular way: {squares}")
Regular way: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Using list comprehensions >>> squares_comprehension = [i**2 for i in range(10)] >>> print(f"Using list comprehension: {squares_comprehension}")
Using list comprehension: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List comprehensions can also contain conditions:

Python 3.13
# Filtering with a condition: only even numbers
>>> even_squares = [i**2 for i in range(10) if i % 2 == 0]
>>> print(f"Squares of even numbers: {even_squares}")
Squares of even numbers: [0, 4, 16, 36, 64]

Understanding check

Let's check how well you've understood the topic of loops:

What result will the following code give?

Python 3.13
total = 0
for i in range(1, 5):
    if i % 2 == 0:
        total += i
print(total)

We are in touch with you
English