Iterations and Loops

Loops let you run the same block of code several times: walk over the elements of a list, repeat an action N times, keep going while a condition holds. Without them you'd have to copy the same logic by hand for every step.

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"Fruit: {fruit}")
Fruit: apple
Fruit: banana
Fruit: cherry

The construct for fruit in fruits takes each element of the list in turn, binds it to the name fruit, and runs the indented body.

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.

The examples below use print(..., end=" "): by default print appends a newline at the end, but the end=" " parameter replaces it with a space so values print on a single line.

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

The loop runs while the condition count <= 5 is true. Inside, you must change the variable from the condition (here count += 1), otherwise the loop will be 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 two main ones are break and continue.

The break statement

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

The loop walks through numbers 0–9, hits break at 5 and exits the loop; numbers 6–9 are not visited

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:

The loop walks through numbers 0–5, hits continue at 3, skips over it, and resumes at 4

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 runs when the loop ends normally (not via break):

Python 3.13
for i in range(5):
    print(i, end=" ")
else:
    print("\nLoop completed without break")
0 1 2 3 4
Loop completed without break

The feature exists, but it's rarely used in real-world code.

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)