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:
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:
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.
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.
By passing two values, you set the start value and the stop value:
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:
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:
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:
Particularly elegant is the creation of a list or a dictionary using a for-loop, which is then usually also defined in a line:
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:
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.
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:
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.
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.
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.
What is Git?
Learn about Git in software development with our comprehensive guide. Find out how Git enables efficient collaboration and version control.
What is a Repository?
Learn about the importance of repositories in software development and version control. Explore best practices and tools for efficient coding.
What is Bitbucket?
Learn about Bitbucket, a powerful Git-based source code management platform for teams - including features and best practices.
What is a NumPy Array?
Efficiently manipulate and analyze data with NumPy arrays for high-performance scientific computing and numerical operations.
How to use the Python Lambdas?
Simplify your code with Python lambda functions for concise and inline anonymous functions in your programming tasks.
What are Tensors in Machine Learning?
Master machine learning with tensors: foundational data structures for efficient computation and deep learning algorithms.
What are Python Operators?
Unlock the power of Python operators: learn how to manipulate data and perform calculations with ease in your code.
What is Numpy?
Unlock the power of NumPy for efficient numerical computations and data manipulation in Python. Accelerate your data analysis workflows.
Python Try Except – easily explained!
Explanation of the try-except loop in Python with code examples.
Pandas Series – easily explained!
Explanation of Pandas Series as opposed to Python list.
Other Articles on the Topic of Python for-loops
- w3schools also offers an interesting post on Python for-loops.