For loops in python

Iterate a python list

country_list = ['Germany', 'France', 'Italy', 'Spain']
for country in country_list:
    print(country)

Will output:

Germany
France
Italy
Spain

Iterate a python dictionary

for key in country_dict:
    print('{1} is the capital of {0}'.format(
        key,
        country_dict[key]
    ))

The output will be:

Berlin is the capital of Germany
Paris is the capital of France
Rome is the capital of Italy
Madrid is the capital of Spain

Iterate a python dictionary with enumerate

for item in enumerate(country_dict):
    print(item)

The value for item will be:

(0, 'Germany')
(1, 'France')
(2, 'Italy')
(3, 'Spain')

As you can see, item will be an item where the first element is the index number and the second element is the dictionary key value for each iteration. To get the capital city for each country using enumerate write:

for item in enumerate(country_dict):
    print('({0}) {1} is the capital of {2}'.format(
        item[0],                # interation index
        item[1],                # dictionary key
        country_dict[item[1]]   # dictionary value for the current key
    ))

The output will be:

(0) Germany is the capital of Berlin
(1) France is the capital of Paris
(2) Italy is the capital of Rome
(3) Spain is the capital of Madrid

Using break to stop a for loop

Let's say we want to iterate only first two elements from our dictionary:

for item in enumerate(country_dict):
    if item[0] > 1:
        break
    print('({0}) {1} is the capital of {2}'.format(
        item[0],                # interation index
        item[1],                # dictionary key
        country_dict[item[1]]   # dictionary value for the current key
    ))

The above code will iterate through the dictionary and will stop after the first two interations. Keep in mind that the first iteration has the index zero (0) and the second interation has the index one (1). This is why the condition is if item[0] > 1:. To stop the iteration of the dictionary we use the break statement.

The output will be:

(0) Germany is the capital of Berlin
(1) France is the capital of Paris

Using continue to skip elements

Let's say that you have a list if dictionaries with the country details but you want to display some information only for one of them:

countries_list = [
    {
        'name': 'Germany',
        'country_code': 'DE',
        'capital': 'Berlin',
    },
    {
        'name': 'France',
        'country_code': 'FR',
        'capital': 'Paris',
    },
    {
        'name': 'Italy',
        'country_code': 'IT',
        'capital': 'Rome',
    },
    {
        'name': 'Spain',
        'country_code': 'ES',
        'capital': 'Madrid',
    },

If you will loop through the countries list, you will write:

for country_dict in countries_list:
    print(country_dict)

and the output will be

{'name': 'Germany', 'country_code': 'DE', 'capital': 'Berlin'}
{'name': 'France', 'country_code': 'FR', 'capital': 'Paris'}
{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}
{'name': 'Spain', 'country_code': 'ES', 'capital': 'Madrid'}

Each element of the iteration will be of type dict (dictionary).

If you are interested to get the details for Italy only, you'll write the for loop like this:

for country_dict in countries_list:
    if country_dict['country_code'] != 'IT':
        continue
    print(country_dict)

The output will be:

{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}

With the above core, you have to take in consideration that the for loop will not stop when it will find the required element. It will continue the iteration for all elements in the list and will skip everything that doesn't satisfy the condition from if statement

To stop the iteration you'll have to use break

for country_dict in countries_list:
    if country_dict['country_code'] != 'IT':
        continue
    print(country_dict)
    break

Or you can change the if condition to a positive form. But doing this, continue will not be necessary any more:

for country_dict in countries_list:
    if country_dict['country_code'] == 'IT':
        print(country_dict)
        break

The output will be the same as above


Using else in a for loop statement

Let's take the last example and look for a country that is not in our list. If the required element was not found, then I want to know about it:

for country_dict in countries_list:
    if country_dict['country_code'] == 'RO':
        print(country_dict)
        break
else:
    print('Required country was not found')

The output will be:

Required country was not found

Now, the tricky part.

The code from else block will be executed when the for loop will finish. The break statement here, makes the for loop NOT to enter into else statment.

If we search for IT for example and remove the break statement to allow to iterate through all elements of the list:

for country_dict in countries_list:
    if country_dict['country_code'] == 'IT':
        print(country_dict)
else:
    print('Required country was not found')

The output will be:

{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}
Required country was not found
Note that break is not anymore below print(country_dict). This will make for loop to continue iteration until the end. Once it finishes, it will enter in else block