For Loop in Python

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 allows 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.

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 of the way they work.

Let’s get started!

Go through a List with a For Loop in Python

Firstly we will see how to use a for loop to go through the items of a Python sequence.

The generic syntax of a for loop is:

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

At every iteration of the loop the code block inside the for loop is executed using 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 occurs, we will see this later in this tutorial…

Here is an example of a for loop:

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

for animal in animals:
    print(animal)

The output is:

lion
tiger
giraffe

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

Using Break and Continue with a Python For Loop

The break statement 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:

lion

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

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

The continue statement skips the current iteration in a for loop and continues executing the code from the next iteration of the loop.

Let’s replace break with continue in our previous example 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 the continue statement skips the second iteration but doesn’t exit from the loop in the way the break statement does:

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 set.

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 machine to see the difference between tuple and set.

For Loop Applied to Strings

A string is a sequence too, it’s a sequence of characters.

For this reason you can also apply a for loop to 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 after each character of the string.

What if we want to print each character without newline?

To print a string in Python without newline 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=' ')

This time the output is:

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

And now let’s move to another data type…

For Loop Applied to a Dictionary

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…

name
nationality

…just the keys of the dictionary.

So from here we can print keys and values:

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/codefather/for_loop.py", line 55, in 
     for name, nationality in user_details:
ValueError: too many values to unpack (expected 2)

We get back a too many values to unpack error.

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!

For Else Loop in Python

If you write a Python program you can use the else clause 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 clause 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 how the break statement changes the behaviour of the else clause 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 to track the index of sequences while going through a for loop.

One way of doing this is with the 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.

We 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 (step).

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 customised.

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 to confirm the output is the one you expect.

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

Nested For Loops in Python

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

This is what we call a nested for loop.

To explain this we will define a matrix (basically 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 the 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 actually 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/codefather/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:

  • The 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.
  • The 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 about for loops in Python.

To recap, we went through:

  • How to loop through a sequence in Python (list, tuple, set, string, dictionary).
  • The break and continue statements used 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.

Happy coding!

Claudio

Share knowledge with your friends!

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *