Remember how in the previous article if instructions in Python were compared to how the human brain makes decisions based on some conditions in everyday life? In the case of for loops, the situation is the same. A person goes through an entire shopping list until he buys everything on it. The dealer deals cards until each player has 5 pieces. An athlete does push-ups until he gets to a hundred… Loops are everywhere. The thing about for loops in Python is that you need them to do repetitive tasks. In this article, you’ll learn everything you need to know about these loops: syntax, logic, and best examples. This is a practical guide! It is advisable to repeat the parts where you need to write code and solve problems at the end of the article! It is also recommended to go back to past materials if you haven’t read them yet.
Table of Contents
For loops in Python: two simple examples
First things first: you need for loops to iterate over iterated objects. In most cases, this will be the familiar lists, strings and dictionaries. Sometimes they can be range()
objects (more about that at the end of the article). Let’s start with the simplest example – list! Freddy’s dog has been used many times in past tutorials. And here he is again, to illustrate the example. Let’s create a list:
dog = ['Freddie', 9, True, 1.1, 2001, ['bone', 'little ball']]
Now that we have a list ready, we can go through all its elements, displaying them one by one with a simple for loop:
for i in dog:
print(i)
The result will be the elements of the list displayed one after the other on different lines:
Freddie
9
True
1.1
2001
['bone', 'little ball']
But what is the advantage of this method? Let’s use another example: a list of numbers:
numbers = [1, 5, 12, 91, 102]
Suppose we want to square each of them. Note: unfortunately, the formula numbers * numbers
won’t work… It seems logical, but once you know Python better, you’ll see that it’s not logical at all. We need to do the following:
for i in numbers:
print(i * i)
The result will be: Here’s what happens step by step:
- We have a list
(numbers
) with 5 elements. - We take the first element (because of the indexing from zero, it will be the 0 (zero) element) of the list
(1
) and store it in thei
variable. - We execute the
print(i * i)
function which returns the value1
squared. This is1
. - Then the whole process starts again..
- We take a new item and assign it to the
i
variable. - Execute
print (i * i)
again and we get the value of the second item in the square:25
- Repeat the process.. …until we get the last element squared.
This is a basic example of how loops work in Python, but it doesn’t get much more complicated than that – only more complex.
The logic behind for loops in Python
Now that the usefulness of for loops is clear, you need to understand the logic behind them. Note: this is one of the most important parts of the manual. Many people have no problem using the basic loops, but have trouble using the more complex ones. The problem is that they learn the syntax, but forget to understand the logic. So it’s a good idea to reread this section until you get the hang of it. In the future you will thank yourself for taking the time to do it. This is a block diagram with a visualization of the loop process: Let’s break it down and study everything in detail. As an example, we will use the previous code with the list
of numbers
and their values squared:
numbers = [1, 5, 12, 91, 102]
for i in numbers:
print(i * i)
- Define the iterable object (that is, the already existing list
numbers = [1, 5, 12, 91, 102]
). - When creating a for loop, the first line will always look something like this
for i in numbers:
for
andin
are Python keywords, andnumber
is the name of the list. But much more important is the variablei
. It is a “temporary” variable, and its only role is to store the specific list item that will work at the time of each separate iteration of the loop. Although in most cases this variable is namedi
(in online courses and even books), it is important to know that you can choose any name you want. It can be not onlyi
(for i in numbers
), but also, for example,x
(for x in numbers
) orhello
(for hello in numbers
). Or any other value. The point is that it is a variable and you have to remember to refer to it inside the loop. - We continue to use numbers as examples. We take the first element of the iterable object (technically, because of indexing from zero, it is 0 (zero) object. This will start the first iteration of the loop. The zero element is
1
. The value of the variablei
will be1
. - The function in the loop was
print(i * i
). Since i = 1, the result ofi * i
will be1
.a 1
is printed to the screen. - The loop starts over again.
- The next element is taken and the second iteration of the loop begins. The first element
of number
is5
. i
equals5
. Againprint(i * i)
is started and25
is displayed.- The loop will start again. The next element.
- One more element. This is the third iteration. The second element is
12
. print(i * i)
will print144
.- The cycle restarts. The next element is present. This is a new iteration.
- The third element is
91
. The value in the square is8281
. - The cycle restarts. The next element is present. New iteration.
i
equals102
. The squared value is10404
.- The loop restarts. But there is no “next element”. The loop ends.
This is a very, very detailed explanation of the third line. But this is only necessary the first time. The next time you’ll have all the logic in your head. But it was important to look into it this way because it is this logic that beginners lack, and this deficiency directly affects the quality of code.
Iteration by strings
You can use other sequences for the loop, not just lists. Let’s try a string:
my_list = "Hello World!"
for i in my_list:
print(i)
It’s easy. The letters are printed one by one. It is important to remember that strings are always treated as sequences of characters, so the for loop handles them the same way it handles lists.
Iterating over range() objects
range()
is a built-in Python function and is almost always used only in for loops. But what for? Simply put, it generates a list of numbers. Here’s how it works:
my_list = range(0,10)
for i in my_list:
print(i)
It takes three arguments:
- the first element: the first element of the range
- the last element: one would assume this is the last element of the range, but it is not. What is actually defined here is the element that will come after the last element. If you enter 10, the range is 0 to 9. If 11 is 0 to 10 and so on.
- the step: this is the difference between the elements of the range. If it’s 2, only every second element will be output.
Can you now guess what the result of the range from above will be? Here it is: Note: the first element and step attributes are optional. If you don’t define them, then the first element is 0 and the default step is 1. Try the following in Jupyter Notebook and check the result:
my_list = range(10)
for i in my_list:
print(i)
Why do you need range()
? In two cases:
- You need to go through the numbers. For example, you want to cube the odd numbers between 1 and 9. No problem:
my_list = range(1, 10, 2) for i in my_list: print(i * i * i)
- You need to go through the list, keeping the indexes of the elements.
my_list = [1, 5, 12, 91, 102] my_list_length = len(my_list) for i in range(0,my_list_length): print(i, my_list[i] * my_list[i])
In this case
i
is the index, and the list elements will bemy_list[i]
.
Either way, range()
will make working with loops in Python easier.
Best Practices and Common Errors
- The for loops are not the easiest of topics for beginners. They require algorithmic thinking to work with them. However, if the problem is really hard, it is better to draw a scheme on paper. Just go through the first iterations on paper and write down the results. This way it will be clearer.
- As in the case of if instructions, you must be careful with the syntax. The colon is obligatory at the end of the
for
line. There must be 4 spaces before the line in the body of the loop. - It is not allowed to
print()
strings and numbers with a+
sign. This is more a peculiarity of theprint
function rather than the for loop, but this problem will most often occur in loops. For example:
If this occurs, it’s best to turn numbers into strings using str()
. Here is a previous example with the correct syntax: That’s it. Now it’s time for an exercise.
Check yourself
Here’s a great exercise for the for loop: Take a variable and assign it a random string. Then print a pyramid of string elements like this example: my_string = "python"
Output:
p
py
pyt
pyth
pytho
python
pytho
pytho
pyt
py
p
Write code that would do the same for any value of my_string
.
Solution
Note: there are several ways to solve this problem. The following will be relatively simple, but you can use more complicated ones.
my_string = "python"
x = 0
for i in my_string:
x = x + 1
print(my_string[0:x])
for i in my_string:
x = x - 1
print(my_string[0:x])
The solution speaks for itself. The only trick is to use the variable-counter “x”, which shows the number of characters needed to output in that iteration. In the first for loop, the value is incremented until it reaches the value of the number of characters in the word. In the second cycle, it goes down to zero until there are no characters left on the screen.
Total
For loops in Python are very important. They are widely used in data science. The syntax is fairly simple, but it takes effort to understand the logic. This article should be enough to get the basics straight, so all that remains is practice. In the next article, you will learn how to combine for loops with each other and for loops with if instructions.