Join my Asyncio (Python) course on Udemy for free 👀

Learn Python for-loops

May 18, 2022  ‐ 5 min read

The Python for-loop loops over the contents of any iterable Python objects. Iterable Python objects include first and foremost list objects, other iterable types include Strings, Tuples and Sets.

For-loops in Python are implemented according to the syntax for <item> in <iterable>:, this is demonstrated in the following example in which we loop over a list of strings:

for letter in ['a', 'b', 'c']:
    print('letter is:', letter)

# => "letter is: a"
# => "letter is: b"
# => "letter is: c"

In the above example we loop over a list of letters that we create on the fly. Each element is available to us inside the for-loop by the variable name we used. In our case we used the variable name letter.

After the last iteration of the for-loop the variable letter is still available to you holding the last value of the list.

# ...

print(letter)
# => "c"

Exit for loops early

Depending on the size of the iterable, loops can be memory and/or time consuming processes. When you don't need to loop through all the items you can choose to exit out of a for-loop early by using the break statement.

By using the break statement you can manually stop processing the items in the for-loop.

for number in [1, 3, 4, 7, 11]:
    if number % 2 == 0:
        print('Found an even number: ', number)
        break
    print(number, 'is odd')

# => "1 is odd"
# => "3 is odd"
# => "Found an even number: 4"

The for-loop above loops over a list of numbers and breaks out of the loop once the expression number % 2 == 0 evaluates as true. As you see, the items in the list that come after this even number are not processed. This is due to the break statements, which makes us exit the for-loop.

If you wish to not exit out of the but just skip the current iteration you should go with the continue statement instead. We cover how to use the continue statement in for-loops below.

Continue to the next iteration

Now, let's discuss a slightly different statement which lets us continue to the next iteration; continue. This statement won't make us break out of the for-loop all together, but it lets us break out of just the current iteration.

In other words, with the continue statement we can continue to the next item in the list or other iterable object.

for number in [1, 3, 4, 7, 11]:
    if number % 2 == 0:
        continue
    print(number, 'is odd')

# => "1 is odd"
# => "3 is odd"
# => "7 is odd"
# => "11 is odd"

In the output of the code snippet above you will notice that the number 4 is skipped. Since the if statement evaluates as true for the number 4 we continue before the print() statement.

The continue statement terminates further execution of the for-loop its body and continues to the next iteration.

In contrast to break we do process the other items in the list.

Access the index in for loops

If you are familiar with C-like languages you probably came across for-loops with a signature like for (i = 0; i < 10; i++). While I personally favour the readability of for-loops in Python, having a variable available which can be used as an index or loop iteration counter can be convenient.

In Python we can get a loop index, starting at 0, by using the enumerate() function.

numbers = ['zero', 'one', 'two', 'three']
for index, number in enumerate(numbers):
    print(index, number)
# => "0 zero"
# => "1 one"
# => "2 two"
# => "3 three"

The enumerate() function gives you two variables for your for-loop; the counter for the current iteration and second the corresponding value for the iteration.

If you are truly looking for a variable that counts instead of an index then maybe you prefer a variant for which you define the counter variable yourselves.

count = 0
for number in [1, 3, 4, 7, 11]:
    if number % 2 == 0:
        continue
    count += 1
print('Found', count, 'odd numbers')
# => "Found 4 odd numbers"

Loop through dictionaries

As I mentioned at the top of this post, we can use for-loops to loop through other types of Python data structures as well. One example that might be useful is looping over the contents of a dictionary.

To loop over key-value pairs of a Python dictionary we use the .items() method available on dictionaries, which returns a tuple with both the key and the value.

numbers = {
    'nul': 'zero',
    'een': 'one',
    'twee': 'two',
    'drie': 'three',
}

for dutch, english in numbers.items():
    print(dutch, 'is Dutch for', english)

Besides looping over the keys and values of the dictionary together, we can loop over the keys or values individually as well.

In order to loop over the keys of a dictionary we use the .keys() method available on dictionaries. This returns the dictionary keys to you as a list.

numbers = {
    'nul': 'zero',
    'een': 'one',
    'twee': 'two',
    'drie': 'three',
}

for dutch_number in numbers.keys():
    print(dutch_number)

# => "nul"
# => "een"
# => "twee"
# => "drie"

To loop over the values of a dictionary the same applies as for keys, but instead we use the .values() method.

numbers = {
    'nul': 'zero',
    'een': 'one',
    'twee': 'two',
    'drie': 'three',
}

for english_number in numbers.values():
    print(english_number)

# => "zero"
# => "one"
# => "two"
# => "three"