Everything About Python for Loop

by:

Python

This post intends to teach you everything about Python for loop. A for loop in Python is used differently than most programming languages. In my honest opinion, I love Python’s for loop and I hope that after reading this blog post, you will love it too.

1. For loop Use

In Python, a for loop is used for iterating over a sequence which can be of different data types such as list, a dictionary (my favorite), a tuple, a, a set, or even a string.

For example, let’s loop over a list of numbers:

my_fav_numbers = [1, 3, 5, 7, 11]

for current_number in my_fav_numbers:
    print(current_number)

If you run the code above, you will notice that you are looping over a list (my_fav_numbers) and printing each of the numbers. Easy, isn’t it? It should print the following numbers.

>>> 1
>>> 3
>>> 5
>>> 7
>>> 11

2. Looping Through a Dictionary

I love looping through a dict. As you may remember a dictionary is a presentation of the data structure named hash table where it has a key and a value. Thus, the cool feature on looping through a hash table is that you can access the value associated with the key from your hash. See the example below.

my_hash = {}

my_hash["Brazil"] = ["Sao Paulo", "Rio de Janeiro", "Recife"]
my_hash["USA"] = ["San Diego", "New York", "Santa Barbara", "Miami"]
my_hash["Japan"] = ["Okinawa", "Tokyo", "Osaka"]

for country_name in my_hash:
    print(country_name, my_hash[country_name])

When you execute the code, it prints the country name and a list of cities from that key country.

>>> Brazil ['Sao Paulo', 'Rio de Janeiro', 'Recife']
>>> USA ['San Diego', 'New York', 'Santa Barbara', 'Miami']
>>> Japan ['Okinawa', 'Tokyo', 'Osaka']

2. Writing Nested Loops

In Python it is very easy to write nested loops, but please don’t get too crazy! We can reuse the dict example to print the country name next to the city name as you see below.

my_hash = {}

my_hash["Brazil"] = ["Sao Paulo", "Rio de Janeiro", "Recife"]
my_hash["USA"] = ["San Diego", "New York", "Santa Barbara", "Miami"]
my_hash["Japan"] = ["Okinawa", "Tokyo", "Osaka"]

for country_name in my_hash:
    for city_name in my_hash[country_name]:
        print(country_name, city_name)
    print()

Which should print the following

>>> Brazil Sao Paulo
>>> Brazil Rio de Janeiro
>>> Brazil Recife

>>> USA San Diego
>>> USA New York
>>> USA Santa Barbara
>>> USA Miami

>>> Japan Okinawa
>>> Japan Tokyo
>>> Japan Osaka

3. Use `break` to Break a For Loop

Let’s say you are looping a list, tuple, dict, or string, and then you decide that you don’t want to finish going through all the iterations of the loop. Luckily, you can use the break command to break the for a loop.

For example, let’s say I want to break my loop when I see a number file in the list.

my_fav_numbers = [1, 3, 5, 7, 11]

for current_number in my_fav_numbers:
    if current_number == 5:
        print("We found 5. Breaking loop!")
        break
    print(current_number)

It should print something like this

>>> 1
>>> 3
>>> We found 5. Breaking loop!

Notice that if 5 is not in the list of the example above, the for loop will finish all the iterations of the loop.

4. Using the continue Statement

Let’s say we want to skip an iteration of the for loop if we don’t something we don’t like. Here we don’t want to break the loop as shown before; Instead, we want to skip an iteration, and what is how we can continue.

On the example below, we want to skip printing the number 5 of our list

my_fav_numbers = [1, 3, 5, 7, 11]

for current_number in my_fav_numbers:
    if current_number == 5:
        continue
    print(current_number)

Which should print the following number, and as you can see the number 5 is not part of it.

>>> 1
>>> 3
>>> 7
>>> 11

In conclusion, I hope this tutorial taught you some lessons on how to use the for loop on Python.

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts