Loop for in Python: understanding and using it

Loop for in Python

The for loop in Python is used to execute a block of code repeatedly . For loops are a fundamental part of most programming languages. We show how the for loop works in Python and how to use it.

  1. What is the for loop in Python?
  2. What makes Python’s for loop different from other languages?
  3. How does a for loop work in Python?
  4. What are the best ways to use for loops in Python?
  5. Replace for loops in Python with comprehensions

What is the for loop in Python?

The for loop is, along with the if-else branch, the best-known programming technique. Generations of programmers have struggled to develop the computing concept of the loop. Indeed, the loops are initially unintuitive . However, the problems of comprehension perhaps stem more from the way in which the concept is presented. Because in themselves, the loops have nothing very particular.

Illustrating the concept of the loop with a concrete example, however, helps understanding. Let’s imagine a school class: the teacher wants to determine the average height of the children as part of an experiment . To do this, he asks each child his height as he goes and adds the different heights to obtain a sum. Then it divides the sum by the number of children to get the average height. We make a simple algorithm from the teacher’s procedure:

  1. Ask for the height of each child and add it to the sum
  2. Divide the sum by the number of children

The first step is performed once for each child and therefore depends on the number of children in the class. The second step is executed only once, regardless of the number of children in the class. We need a loop for the first step. Here is sample code that calculates the average height of a schoolboy with a for loop in Python:

children_heights = [155, 171, 148, 161, 158, 153, 162]
height_sum = 0
for height in children_heights:
    height_sum = height_sum + height
average_height = height_sum // len(children_heights)
The for loop in Python executes a block of code repeatedly. This is also referred to as “iteration”. In particular, loops make it possible to individually process, according to the same scheme, several elements grouped together in the same “collection” . A for loop is therefore used when all the elements of the collection can be determined during program execution. If not, then a while loop is recommended.

What makes Python’s for loop different from other languages?

Many programming languages ​​are familiar with the concept of the for loop. It is a fundamental construct in other languages ​​like C, Java, JavaScript and PHP. Purely functional languages ​​like Haskell or Lisp usually don’t have a for loop. Instead of iteration, these languages ​​use recursive functions.

All loops have one thing in common: a block of code is executed repeatedly. However, the way the for loop works in Python is quite distinct from other . Most programming languages ​​use a loop variable which is incremented or decremented when the loop is executed.

Stock Meaning Ordinary representation Representation in Python
Increment Increase the value of an integer variable by a specified fixed amount i++ index += 1
Decrement Decrease the value of an integer variable by a specified fixed amount i– index-=1

Let’s take an example to see how a for loop works in other languages. We first take the numbers from 0 to 9 in JavaScript with a for loop. An integer variable ‘number’ is then defined and it is incremented as long as the number it contains is less than 10. The code used for this operation seems rather complex for beginners:

<spanfor ( let number = 0; number < 10; number++ ) {
<span    console.log(number);

While the code for a corresponding for loop in Python looks significantly clearer:

<spanfor number in range(10):
<span    print(number)

Instead of displaying the value of the loop variable directly, it is typically used to index an item within a collection. Let’s take another example in JavaScript: we display the names contained in the ‘people’ list one after the other. For this, we use the loop variable ‘i’ as a continuous index of the different elements:

<spanpeople = ['Jack', 'Jim', 'John']
<spanfor (let i = 0; i < people.length; i++) {
<span    console.log("Here comes " + people[i]);

Indexing sequential list items directly should be done with caution. Indeed, an access attempt outside the authorized limits results in a runtime error. As a rule, this is the famous “Off-by-one Error”. Python shows that it is possible to do otherwise. Here is the same example with a for loop in Python: we iterate directly over the elements of the list , without indexing them with a loop variable:

<spanpeople = ['Jack', 'Jim', 'John']
<spanfor person in people:
<span    print(f"Here comes {person}")

The indirect value of the loop variable contributes greatly to the complexity of learning for loops in other languages. Indeed, the central loop variable is generally of no interest to us . It is only used to index the different elements. Using traditional for loops requires understanding several complex topics. Let’s take the example of JavaScript:

Theme Representation in the JavaScript for loop
Declare a variable let i = 0
Boolean expressions i < limit
Increment and decrement tool i++ / i–
Determine the size of a collection i < list.length
Indexing items from scratch i < list.length is OK; i <= list.length leads to Off-by-one Error

The for loop in Python is much easier to use. Even though the ‘for’ keyword is used, this is a fundamentally different approach. Instead of incrementing a variable in the loop and thus successively indexing elements, we iterate directly over the elements of a collection . The for loop in Python is thus comparable to the forEach construction of certain languages ​​like Ruby and JavaScript.

To illustrate our point, let’s give the different letters of a word. In the for loop, a letter of the word is placed in the ‘letter’ variable each time the loop passes. It works without a loop variable and therefore without risk of producing an off-by-one error. The code is precise and easy to read:

<spanword = "Python"
<spanfor letter in word:
<span    print(letter)

How does a for loop work in Python?

As we have seen, the for loop in Python effectively solves the problem of iterating over the elements of a collection . To do this, we therefore do not need to go through a numeric loop variable. This is certainly a very good point, but how exactly does it work? To understand how the for loop works in Python, you need to know the concepts of iterable and iterator.

What are iterable, iterator and generator?

Python’s for loop operates on objects known as “iterables” . These include strings, lists, tuples, and other composite data types. In the words of the official Python documentation:


“[An iterable is] an object capable of returning its members one at a time”/ Source: docs.python.org/3/glossary.html

Translation: “[An iterable is] an object whose values ​​can be traversed one by one” (translated by IONOS)

An iterable object has two properties:

  1. It groups several elements to form a collection
  2. It gives access to its elements via an interface called “iterator”

Together, this means that iterables are collections whose content can be iterated over. An iterable specifically has an ‘__iter__()’ method that returns an iterator. The iterator is an object that supplies the next element of the iterable on command . Additionally, an iterator recalls the position of the last element returned in the collection.

Function Explanation Example
iter(collection) Calls the __iter__() method of the collection it = iter(“Python”)
next(iterate) Calls the iterator’s __next__() method next(it)
collection[index] Calls the __getitem__(index) method of the collection ‘Python'[1]

An iterator returns to the next element when calling the __next__() method. If all elements of the collection have been delivered , the iterator is exhausted. Another call to __next__() raises a ‘StopIteration’ exception.

Let’s consider how an iterator works using an example . We create a range() object that represents consecutive numbers 21 to 23. Then we create an iterator using the iter() function and we output successive elements using the next() function. On the last call, the exception is thrown because the iterator is exhausted:

<spannumbers = range(21, 24)
<spannumber = iter(numbers)
<span# returns '21'
<span# returns '22'
<span# returns '23'
<span"># raises 'StopIteration' exception

An iterator provides access to individual elements of a collection. Python also knows the similar concept of “generator”. The difference is that a builder only creates individual items at access time . Above all, this saves memory during the execution of the program, which is why we also speak of “lazy generation”.

A generator in Python is based on a function that uses the Yield statement. This returns an object in the same way as the return statement and terminates the function call . On a new call, however, the generator function does not start again from the beginning, but continues after the last yield statement.

The following example illustrates this point. We write our own version of the range() function . We use the yield statement in a while loop to generate continuous numbers:

<spandef my_range(start, stop):
<span    if stop < start:
<span        return None
<span    current = start
<span    while current < stop:
<span        yield current
<span        current += 1
<span# test
<spanassert list(my_range(7, 9)) == list(range(7, 9))

Skipping and undoing a pass of the for loop in Python

In practice, it is sometimes necessary to skip a single pass of the loop. Like many other languages, Python contains the “continue” statement. When calling continue in the loop body, the current iteration is terminated . The loop then immediately begins the next iteration.

A continue statement can be used similarly to early-return when calling a function . For example, we skip an iteration as soon as we find that a dataset does not have the required quality:

<spandef process_data(data):
<span    for data_set in data:
<span        data_set.validate()
<span        # early continue after cheap check fails
<span        if not data_set.quality_ok():
<span            continue
<span        # expensive operation guarded by early continue
<span        data_set.process()

Another example: we take a text and skip every other letter :

text = 'Skipping every second letter'
for index, letter in enumerate(text):
    if index % 2 != 0 and letter != ' ':

In addition to the continue statement to skip a passage of the loop, there is the break statement. A call to break inside the loop body immediately breaks further execution of the loop . Thus, break has a similar function for loops as the return statement for functions.

The break statement is often used to implement search algorithms. If a searched element is found in a loop, there is no need to continue iterating. In the same way as for the any() function, we check the presence of a single True value in a list. With break, we stop as soon as we have found something:

bool_list = [False, False, True, False]
for index, boolean in enumerate(bool_list):
    if boolean:
        print(f"Value at position {index + 1} is True")
        print(f"Aborting inspection of remaining {len(bool_list) - index - 1} item(s)")

Related to the break statement, a for loop in Python can have an optional else body. The code it contains is executed when the loop ends without a break statement having been executed:

def find_element(target, collection):
    for element in collection:
        if element == target:
            print("Found what you’re looking for")
        print("Didn’t find what you were looking for")
# test
find_element('a', 'Python')
find_element('o', 'Python')

For loops are often used in Python inside function bodies. In this case, it is common to use a return statement instead of a break statement . Our search algorithm rephrases without using break and else:

def find_element(target, collection):
    for element in collection:
        if element == target:
            print("Found what you’re looking for")
            # returning breaks us out of the loop
            return element
    # we made it here without returning
    print("Didn’t find what you were looking for")
    return None
# test
print(find_element('a', 'Python'))
print(find_element('o', 'Python'))

What are the best ways to use for loops in Python?

For loops in Python are primarily used to iterate over the elements of a sequence or collection . There are more direct methods for many common application cases. We present best practices and important antipatterns. First, an overview of key terms:

Term Explanation Example
Collection Grouping of several elements; a collection is an iterable (‘Walter’, ‘White’), [4, 2, 6, 9], ‘Python’
Iterator Interface to iterate over collections it = iter(‘Python’)
Generator A function that uses yield instead of the return statement; a generator is iterable range(10)
Understanding Iterative expression; creates a new collection based on an iterable [num ** 2 for num in range(10)]

Iterate directly over the elements of a collection

common mistake made by inexperienced programmers is to abuse the for loop in Python. As is often the case in other languages, they use the len() function as the limit of the range() function to create a looping numeric variable. They use it to index the different elements of the collection:

word = 'Python'
for i in range(len(word)):

This antipattern is frowned upon for a good reason: it’s not Pythonic . Indeed, it is preferable to iterate directly over the elements of the collection with Python’s for loop:

word = 'Python'
for letter in word:

Enumerate elements of a collection with enumerate() and their index

Sometimes we need the index of an element in a collection . Instead of creating the index as a loop variable, we use the enumerate() function. This returns the tuple (index, element). Note that the index starts counting from zero:

names = ["Jim", "Jack", "John"]
for index, name in enumerate(names):
    print(f"{index + 1}. {name}")

Use the zip() function to iterate over tuples of elements.

Another frequently encountered scenario is iterating over the elements of two collections of the same length at the same time . The Python approach uses the zip() function. This takes two collections of the same length and successively returns 2 tuples:

people = ('Jim', 'Jack', 'John')
ages = (42, 69, 13)
# ascertain both collections are same length
assert len(people) == len(ages)
# iterate over tuples of (person, age)
for person, age in zip(people, ages):
    print(f"{person} is {age} years old")

Create a numeric variable in a loop with the range() function

Normally, for loops are used in Python to iterate over the elements of a collection. Incrementing an integer with a for loop is in Python rather a special case. The correct way to do this is to construct a range object with the range() function and iterate over that object:

for counter in range(10):

Test if a collection contains an element with the in operator

Finding a specific item in a collection is part of a programmer’s standard repertoire. Normally a function is used to iterate over the items and check that each item is the same as the one you are looking for . If the element is found, then the iteration is interrupted.

In Python, the in operator exists for this frequent case. The operator checks if the collection contains the searched element and returns a corresponding boolean value:

'a' in 'Python'
'y' in 'Python'

Create a list from an iterable with the list() function

Unlike many other languages, there is no need to use a for loop in Python to write the letters of a string one by one into a list. Instead, we use the list() function to convert an iterable to a list of items. Let’s take a look at both approaches with an example. We iterate over the letters of a word and add them to an empty list:

word = 'Python'
letters = []
for letter in word:

We can spare ourselves this effort. We directly create the list with the list() function . At the same time, we check with the assert statement that the two methods give the same result:

assert list(word) == letters

Here is another example: we create the list of numbers from zero to nine . A range object serves as the base as an iterable:


In addition to lists, it is also possible to create sets , in English “sets”, from an iterable. For example, we create a set that reflects the letters contained in a sentence. Next, we check with the in operator that the set of letters does not contain ‘a’:

alphabet = set('Python is not hyped')
assert 'a' not in alphabet

Replace for loops in Python with comprehensions

A common use of for loops in Python is to modify the elements of a collection. If so, we would like calculate new values ​​based on a collection or filter certain items based on a pattern. We describe the different steps following the imperative programming style:

  1. Iterate over the collection with the for loop
  2. Process each element
  3. Optionally, group a subset of items into a new collection

For simple modifications, it takes a lot of work. Functional languages ​​show that it is possible to make things simpler. Fortunately, Python knows the concept of “comprehensions”. Comprehensions can replace simple uses of the for loop in Python and are sometimes even more efficient.

comprehension generates a collection, possibly modified, based on an iterable . A concise and expressive syntax is used. Consider the general syntax of a list comprehension. The expression is written in square brackets. An operation is performed on the elements of a collection; each item is copied into a new list:

[ operation(element) for element in collection ]

It is also possible to filter elements according to certain patterns, here with if-condition:

[ operation(element) for element in collection if condition(element) ]

Now consider an example of a For loop in Python, which can be replaced with a comprehension . We have a list of numbers and we want to calculate the corresponding list of squares:

numbers = [2, 3, 5, 9, 17]

We create an empty list and fill it with the squares in a for loop :

squares = []
for number in numbers:
    squares.append(number ** 2)

More simply, the list of squares can be expressed as a comprehension :

squares_comp = [number ** 2 for number in numbers]

Next, we use the assert statement to ensure that both methods yield the same result :

assert squares == squares_comp

Here’s another example: we want to extract lowercase letters from a string . As input, we create a list of upper and lower case letters:

word = list("PyThoN")

The traditional way to extract lowercase letters is to iterate over the letter. We test each letter with the islower() function and, if the result is positive, we add it to an initially empty list:

lowers = []
for letter in word:
    if letter.islower():

We can do without this for loop in Python. We instead use a comprehension that copies only lowercase letters from the initial list:

lowers_comp = [ letter for letter in word if letter.islower() ]

We again check the equality of the two methods using the assert statement:

assert lowers == lowers_comp
Top online courses in Teaching & Academics

Related Posts

Leave a Reply