for loop in Python: clearly explained!

Hey there! In this article, we’ll talk about the for loop in Python. It allows you to work with collections like lists, strings, sets, and dictionaries:

for name in ["John", "Mia", "Mike"]:
    print(name)

Output:

John
Mia
Mike

for loop with range

If you want to run a block of code a specific number of times, you can use the range function.

By default, the range function returns a sequence of numbers, starting from zero:

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

Program output:

0
1
2

You can also specify a starting number:

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

Output:

2
3
4

You can also adjust the step of the loop by passing a third argument to the range function:

for i in range(2, 9, 3):
    print(i)

Output:

2
5
8

What’s the output of this Python code?

for i in range(3, 15, 4):
    print(i)
3, 7, 11, 15
3, 7, 11
3, 7, 11, 14
7, 11, 14, 17

for loop through a string

In Python, you can use the for loop to iterate through a string. The code block will run for each character:

name = "John"

for letter in name:
    print(letter)

Output:

J
o
h
n

The break statement

Python allows you to stop the loop at any time. You just use the break keyword:

for i in range(10):
    if i == 3:
        print("Not going beyond this")
        break

    print(i)

Output:

0
1
2
Not going beyond this

The continue statement

If you don’t want to stop the loop entirely but just skip one iteration, you can use the continue keyword:

for i in range(5):
    if i == 3:
        print("3 won't do")
        continue

    print(i)

Output:

0
1
2
3 won't do
4

From the example, you can see that the for loop continued running, skipping just one element. In this instance, you could use just if-else:

for i in range(5):
    if i == 3:
        print("3 won't do")
    else:
        print(i)

But I prefer the version with continue, especially when we have lots of instructions that need to be executed in the loop. continue helps remove the nesting level that arises from using else.

What’s the output of the following Python code?

for i in range(5):
    if i == 2:
        continue
    elif i == 4:
        print("Wrapping it up")
        break

    print(i)
0 1 2 3 4 Wrapping it up
0 1 3 Wrapping it up
0 1 2 3 Wrapping it up
0 1 3 4 Wrapping it up

for-else

Did you know that the else keyword can be used not only with if but also with for? Check this out:

for i in range(3):
    print(i)
else:
    print("Done!")

Output:

0
1
2
Done!

But now, let’s add break:

for i in range(3):
    if i == 2:
        break
    print(i)
else:
    print("Done!")

Now the output is different:

0
1

There’s no “Done!” this time. That’s because the else after for only executes if the loop processed all items without hitting a break. And by the way, continue doesn’t affect the else:

for i in range(3):
    if i == 2:
        continue
    print(i)
else:
    print("Done!")

Output:

0
1
Done!

What will be displayed?

for i in range(5):
    if i % 3 == 0:
        continue
    elif i == 4:
        break
    print(i)
else:
    print("Done!")
0
1, 2
1, 2, Done!
1, 2, 3

nested loops

You can use a for loop inside another for loop:

for i in range(1, 3):
    for j in range(1, 3):
        print(i, "*", j, "=", i * j)

Output:

1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4

And yeah, you can nest them as deep as you like.

The pass statement

If you ever think “I don’t really want to do anything in this loop”, then pass is your friend:

for i in range(100):
  pass

This code won’t do a thing.

Using enumerate with for

Ever needed to know the index of an item in a for loop? Just wrap the list in the enumerate function:

names = ["John", "Mia", "Mike"]

for i, name in enumerate(names):
    print(i, name)

Output:

0 John
1 Mia
2 Mike

You can even choose the starting number for enumerate with the start argument.

What’s the output of this Python code?

students = ["James", "Ava", "Oliver"]

for idx, student in enumerate(students, start=1):
    print(idx, student)
0 Ava, 1 Oliver
1 Ava, 2 Oliver
0 James, 1 Ava, 2 Oliver
1 James, 2 Ava, 3 Oliver

Using a for loop with dictionaries

Need to loop through the values in a dictionary? No worries. The for loop handles this with ease:

ages = {
    "John": 18,
    "Mia": 22,
    "Mike": 26,
}

for name in ages:
    print(name, ages[name])

Output:

John 18
Mia 22
Mike 26

With this, we can directly get both the name and age:

for name, age in ages.items():
    print(name, age)

Output:

John 18
Mia 22
Mike 26

If we’re only interested in the ages, we can use the .values() method:

for age in ages.values():
    print(age)

Output:

18
22
26

Iterating in reverse order

If for some reason we want to loop through items in reverse, we can wrap the items in the reversed function:

for i in reversed(range(1, 4)):
    print(i)

Output:

3
2
1

For the range, we can simply pass a negative step to get items in reverse:

for i in range(3, 0, -1):
    print(i)

The output for this program is identical to the previous one.

What will be displayed on the screen?

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

One-liner for loops

If you need to execute only one instruction, you can use the shorthand version of the for loop:

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

Output:

0
1
2

Exercises

  1. Basic for loop usage with different collection types:
    Use different collection types (list, string, set, dictionary) and write a Python program where you use a for loop to display each collection element. Your program should handle each collection type correctly.

  2. Exploring the range function with different parameters:
    a) Write a program that uses the for loop and range to display numbers from 5 to 15.
    b) Write a program that displays every third number in the range of 10 to 25.

  3. Controlling loop execution with break:
    Write a program with a list of 10 names. Your task is to loop through the list of names using a for loop, and as soon as you encounter the name “Dima”, the program should display “Found Dima!” and exit the loop. If “Dima” isn’t in the list, the program should display “Dima not found”.

Discussion

© 2023, codelessons.dev