Skip to content

Python for-Loop – easily explained!

The Python for-loop is used to iterate dynamically over a sequence of objects and to perform calculations with them, for example. It automatically deals with different lengths of the objects and can thus save work in programming.

Why do you need a for-loop?

In the Python programming language, for-loops are used mainly for working with Python Lists, in order to change the objects within the list or to be able to use them for another calculation. The advantage of using the loop is that it is not necessary to know the length of the list or the individual indices of objects.

The for-loop in Python differs massively from those known in other programming languages. In these, it is only used as an alternative to the while loop, i.e. to perform a calculation as long as a condition is met. In Python, on the other hand, it is intended specifically for working with objects and especially lists.

What is the syntax of Python for-loop?

The structure of a for-loop is always relatively similar and begins with the word “for”. This is followed by the variable name, whose value changes with each run. In our case, we call this “variable” and run through the object “object”. In each pass, the variable takes the value of the element that is currently in the queue. The word “in” separates the variable name and the name of the object being traversed:

Python for-Schleife

The line ends with a colon and the next line then starts with an indentation. Each line that is indented after the for statement is executed in one pass. Here, calculations can be executed or, as in our example, simply the elements of the list can be output:

Python for-Schleife

What is the range() function?

If you don’t want to use the for-loop for iteration over a concrete object, but only so that a command is executed multiple times, then the range() function is used. It is written instead of the object name and defines a range of values that is iterated through. There are three specifications for this function: range(start, stop, step). So you can specify at which number the function should start, this is by default 0. In addition, you can specify at which value the function should stop and how large the step size is, here the default is 1.

Python for-Schleife

If you pass only one value to the range() function, then this is automatically the stop value with start value 0 and step length 1.

Python for-Schleife

By passing two values, you set the start value and the stop value:

Python For-Schleife

How can more complex for-loops be formed?

As already described, all lines of code that are indented after the for loop are executed in each pass. This allows you to map more complex relationships and include an if-else loop, for example:

Python for-Schleife

How to write the for-loop in one line?

So far we have learned that the Python for-loop always has a line break after the colon and continues with an indentation on the next line. To make the code more compact or to save time, there is also the possibility to write a Python for-loop in a single line, depending on how complex it is. The example above, which outputs the numbers between 2 and 5, can be written very easily in a single line:

Python for-Schleife

With more complex for-loops, the representation in one line can also quickly become confusing, as our example with the even and odd numbers shows:

Python for-Schleife

Particularly elegant is the creation of a list or a dictionary using a for-loop, which is then usually also defined in a line:

Python for-Schleife

If you were to solve this with a “regular” Python for-loop, you would first have to create an empty list and then fill it bit by bit. This is much more cumbersome:

Python for-Schleife

What do break and continue do in a for-loop?

A Python for-loop should not always run to the end of the loop. In some cases, it can also make sense to end the sequence early. For this purpose, you can use the “break” command. In the following example, the loop is interrupted as soon as the current number is greater than 4.

Python for-Schleife

The command “continue” is the exact opposite of “break” and causes the loop to continue running. It makes sense especially if you do not have a direct command to execute for a condition, but just want to start a round in the loop.

In the following example, we only want to output the numbers that are greater than four. To do this, we skip all values that are less than or equal to four using “continue”. This will output only the numbers from five upwards:

Python for-Schleife

How does enumerate work in a loop?

With the help of “enumerate” you can not only iterate through the elements of an object, such as a list but also get the index of the respective element at the same time. This can make sense, for example, if you want to change the elements of a list directly.

Suppose we want to multiply each odd number in the “numbers” list by two. To do this, we iterate through the “numbers” object using “enumerate” and change the number in the list if the element is odd. It is important to note here that we must now assign two names since each iteration step has two variables, namely the index and the element itself.

Python for-Schleife

Here it is important to understand that changes to the object you are iterating over have no effect on the Python for-loop. It still looks at the object as it did on the very first pass. The following command would otherwise have to result in an infinite loop since the “numbers” element becomes twice as long in each pass as it was before. Nevertheless, the Python for-loop has only nine steps, because at the start of the loop the object “numbers” had only nine elements.

Python for-Schleife

This is what you should take with you

  • The Python for-loop is used to iterate dynamically through elements of an object.
  • With the help of “break” you can end a loop prematurely.
  • The command “enumerate” not only returns an element in each round but also the index of the element in the object. This makes it possible, for example, to change the object from within the loop.
Conditional Statements in Python / If else Python / Bedingte Anweisung

What are Conditional Statements in Python?

Learn how to use conditional statements in Python. Understand if-else, nested if, and elif statements for efficient programming.

XOR

What is XOR?

Explore XOR: The Exclusive OR operator's role in logic, encryption, math, AI, and technology.

Python Exception Handling / Ausnahmebehandlung in Python

How can you do Python Exception Handling?

Unlocking the Art of Python Exception Handling: Best Practices, Tips, and Key Differences Between Python 2 and Python 3.

Python Modules

What are Python Modules?

Explore Python modules: understand their role, enhance functionality, and streamline coding in diverse applications.

Python Comparison Operators / Python Vergleichsoperatoren

What are Python Comparison Operators?

Master Python comparison operators for precise logic and decision-making in programming.

Python Input / Python Output

What are Python Inputs and Outputs?

Master Python Inputs and Outputs: Explore inputs, outputs, and file handling in Python programming efficiently.

Das Logo zeigt einen weißen Hintergrund den Namen "Data Basecamp" mit blauer Schrift. Im rechten unteren Eck wird eine Bergsilhouette in Blau gezeigt.

Don't miss new articles!

We do not send spam! Read everything in our Privacy Policy.

Niklas Lang

I have been working as a machine learning engineer and software developer since 2020 and am passionate about the world of data, algorithms and software development. In addition to my work in the field, I teach at several German universities, including the IU International University of Applied Sciences and the Baden-Württemberg Cooperative State University, in the fields of data science, mathematics and business analytics.

My goal is to present complex topics such as statistics and machine learning in a way that makes them not only understandable, but also exciting and tangible. I combine practical experience from industry with sound theoretical foundations to prepare my students in the best possible way for the challenges of the data world.

Cookie Consent with Real Cookie Banner