For Loop in Python: A Simple Guide

The for loop in Python is one of the main constructs you should be aware of to write flexible and clean Python programs.

The Python for loop is a control flow statement that you can use to iterate over a sequence (e.g. a string, list, tuple, dictionary, set, string). The for statement executes a specific block of code for every item in the sequence. A great feature of for loops in Python is that the same code can work without changes with multiple data types.

In this Python tutorial, we will go through many concepts related to for loops in Python that will give you not only a basic understanding of loops but also a deeper insight into the way they work.

Let’s get started!

Iterate through a Python List: For Loop Syntax

First of all, we will see how to use a for loop to iterate through the items of a Python sequence.

The generic syntax of a for loop is following:

for {item} in {sequence}:
    {code_block}

Note: make sure to respect the correct indentation of the loop body (code_block in the example above) inside the for loop.

At every iteration of the loop, the code block inside the for loop is executed and it’s applied to the item in the sequence. The for loop ends once there are no more items in the sequence.

The execution of the loop might end even before the end of the sequence if specific conditions occur, we will see this later in this tutorial.

The following example of code shows a for loop that iterates through the elements of a Python list:

animals = ['lion', 'tiger', 'giraffe']

for animal in animals:
    print(animal)

The output is:

lion
tiger
giraffe

The behavior of a for loop can be modified using the break and continue statements.

Using Break Statement and Continue Statement with a Python For Loop

The break statement in Python stops the execution of a for loop and continues executing the code after the loop.

animals = ['lion', 'tiger', 'giraffe']

for animal in animals:
    if animal == 'tiger':
        break
    else:
        print(animal)

We use an if else statement to break out of the loop or print the item of the list based on a condition.

The output is the following because the execution of the for loop breaks at the second element of the list when the value of the variable animal is equal to the string ‘tiger’:

lion

In our previous example, we can also omit the else statement:

for animal in animals:
    if animal == 'tiger':
        break
    print(animal)

And now let’s more to the “continue” statement…

The continue statement is used to skip the current iteration in a for loop and to continue executing the code from the next iteration of the loop.

Let’s replace break with continue in the previous example of code and see what happens:

for animal in animals:
    if animal == 'tiger':
        continue
    print(animal)

This time our code also prints the third element of the list because Python’s continue statement skips the second iteration but doesn’t exit from the loop in the way the break statement does.

This means that the loop continues its execution and prints the third element of the list.

lion
giraffe

For Loop Applied to Tuples and Sets

The power of the implementation of the Python for loop is that it can be applied to any type of sequence, for example to a tuple or a set.

Tuple

animals = ('lion', 'tiger', 'giraffe')

for animal in animals:
    print(animal)

Set

animals = {'lion', 'tiger', 'giraffe'}

for animal in animals:
    print(animal)

You can see how the way we write the for loop doesn’t change with lists, tuples, or sets.

One thing that changes is the output of the code when applied to a set considering that sets are unordered and unindexed.

Before continuing run the code on your computer to see the difference between a tuple and a set.

For Loop Applied to Python Strings

A Python string is a sequence too, it’s a sequence of characters. For this reason, you can also apply a for loop to a string.

Let’s write a for loop that iterates through the characters of a string:

website = 'codefather.tech'

for character in website:
    print(character)

Here is the output:

c
o
d
e
f
a
t
h
e
r
.
t
e
c
h

The print statement automatically adds a newline character after each character of the string.

What if we want to print each character without newline?

To print a string in Python without a newline character you can pass the end= argument to the print() function.

In this case, we will remove the newline and have a space between each character:

website = 'codefather.tech'

for character in website:
    print(character, end=' ')

As you can see below, the output of our code has changed:

c o d e f a t h e r . t e c h 

And now let’s move to another data type…

Iterate Through a Python Dictionary With a For Loop

Wonder how the for loop can be used with a dictionary?

Let’s find out!

user_details = {'name': 'Claudio', 'nationality': 'italian'}

for user_detail in user_details:
    print(user_detail)

When you run this you get back the following:

name
nationality

We are getting back just the dictionary keys.

From here we can print the keys and values of the dictionary:

for user_detail in user_details:
    print(user_detail, ":", user_details[user_detail])


[output]
name : Claudio
nationality : italian

Let’s try something different:

for key, value in user_details:
    print(name, nationality)

Hmmm…it doesn’t work…

Traceback (most recent call last):
File "/opt/python/codefathertech/for_loop.py", line 55, in
for name, nationality in user_details:
ValueError: too many values to unpack (expected 2)

We get back the error “too many values to unpack“.

To make it work we have to use the dictionary items() method. Here is what this method returns for our dictionary:

print(user_details.items())
dict_items([('name', 'Claudio'), ('nationality', 'italian')])

Let’s apply it to our for loop to get back keys and values from the dictionary:

for key, value in user_details.items():
    print(key, ":", value)

[output]
name : Claudio
nationality : italian

Great, it works!

Using the Else Statement in a For Loop: How Do You Do It?

If you write a Python program you can use the else statement together with a for loop.

Here’s how…

animals = ['lion', 'tiger', 'giraffe']

for animal in animals:
    print(animal)
else:
    print("For loop executed")

When used with a for loop, the code in the else statement is executed once the for loop is complete. The only exception is if a break statement stops the execution of the loop.

lion
tiger
giraffe
For loop executed

Now have a look at how the break statement changes the behavior of the else statement when used with a for loop:

animal_to_find = 'tiger'

for animal in animals:
    if animal == animal_to_find:
        print(animal_to_find,"found")
        break
else:
    print("Animal not found")

The output is:

tiger found

The code inside the else clause is not executed when a break statement stops the execution of a for loop.

Let’s confirm that the else block is executed if the break statement is not executed:

animal_to_find = 'elephant'

for animal in animals:
    if animal == animal_to_find:
        print(animal_to_find,"found")
        break
else:
    print("Animal not found")

The output of our program confirms that:

Animal not found

Confirmed!

For Loop With Index

So far the for loop we have seen is very different from the for loop used in other programming languages like C where an index is present in the loop definition.

Python also allows tracking of the index of sequences while going through a for loop.

One way of doing this is with the Python range() built-in function (that to be precise, as explained here, is not strictly a function).

Before using range() with a for loop let’s find out what range() returns:

>>> print(range(10))
range(0, 10)
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list(range(1,10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list(range(1,10,2)))
[1, 3, 5, 7, 9] 

The first print statement doesn’t tell us much, so to find out what range() returns we can convert it into a list using Python’s list() built-in function.

You can see that:

  • range(10) returns numbers from 0 to 9 (10 is excluded).
  • range(1,10) returns numbers from 1 to 9.
  • range(1,10,2) returns only odd numbers from 1 to 9 because we are passing a third argument (the step between each number).

The range function returns a sequence of numbers starting from 0 by default, incremented by 1, and ending with the number passed to the function minus 1. The start value and the increment (step) can be customized.

Considering that range() generates a sequence of numbers we can use it to generate the indexes of a list (or tuple, or set, etc….) as part of a for loop.

To do that we use the range function with the len function:

animals = ['lion', 'tiger', 'giraffe']

for index in range(len(animals)):
    print(animals[index])

Give it a try!

Another way to track the index of a sequence in a for loop is with Python enumerate.

Learn Python Nested For Loops

There might be scenarios in which you need to use a for loop inside another.

A for loop inside another for loop is called a nested for loop.

To explain this we will define a matrix (a list of lists that contains numbers):

matrix = [[1,2,3],[4,5,6]]

for row in matrix:
    for value in row:
        if value == 2:
            print("Number 2 found in the matrix")

[output]
Number 2 found in the matrix

The outer loop selects one row at a time and the inner loop goes through values in each row.

Another option is to use the range() function to track rows and columns of the matrix:

for row in range(len(matrix)):
    for column in range(len(matrix[row])):
        print("Row:",row,"Column:",column,"Value:",matrix[row][column])

In this case, we track indexes for rows and columns and hence we can print them:

Row: 0 Column: 0 Value: 1
Row: 0 Column: 1 Value: 2
Row: 0 Column: 2 Value: 3
Row: 1 Column: 0 Value: 4
Row: 1 Column: 1 Value: 5
Row: 1 Column: 2 Value: 6

Be careful when you work with indexes in nested loops, it’s quite easy to use invalid indexes by mistake like in the following case. And these errors are not always easy to find:

for row in range(len(matrix)):
    for column in range(len(row)):
        print("Row:",row,"Column:",column,"Value:",matrix[row][column])

This code returns the following error:

Traceback (most recent call last):
File "/opt/python/codefathertech/for_loop.py", line 103, in
for column in range(len(row)):
TypeError: object of type 'int' has no len()

Can you see where the error is?

I will leave it to you to find out… 🙂

Definite and Indefinite Iteration

A short digression before finishing this tutorial…

Python provides different types of loops:

  • for loop: based on definite iteration. We use the term definite because a block of code or set of instructions is repeated a fixed number of times.
  • while loop: based on indefinite iteration. In this case, a block of code is repeated as long as a logical condition is met.

So, now you know what these terms refer to if you hear them in the future.

Conclusion

After this tutorial, you should have a very good knowledge of for loops in Python and this will help you improve your overall Python programming skills.

To recap, we went through:

  • How to loop through a sequence in Python (list, tuple, set, string, dictionary).
  • Using the break and continue statements with for loops.
  • Using the else statement with a loop.
  • Tracking indexes in for loops using the range() and len() functions.
  • Nested loops and definite/indefinite iteration.

The full source code created in this tutorial is available here.

Related article: There is also a more Pythonic way to iterate through sequences. To know more have a look at the CodeFatherTech tutorial about Python list comprehensions.

Leave a Comment