#5 Python for Data Science – parsing the for loop

by Alex
#5 Python for Data Science - parsing the for loop

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.

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:

  1. We have a list(numbers) with 5 elements.
  2. 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 the i variable.
  3. We execute the print(i * i) function which returns the value 1 squared. This is 1.
  4. Then the whole process starts again..
  5. We take a new item and assign it to the i variable.
  6. Execute print (i * i) again and we get the value of the second item in the square: 25
  7. 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: Логика циклов for в Python 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)
  1. Define the iterable object (that is, the already existing list numbers = [1, 5, 12, 91, 102]).
  2. When creating a for loop, the first line will always look something like this
    for i in numbers:
    

    for and in are Python keywords, and number is the name of the list. But much more important is the variable i. 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 named i (in online courses and even books), it is important to know that you can choose any name you want. It can be not only i(for i in numbers), but also, for example, x(for x in numbers) or hello(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.

  3. 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 variable i will be 1.
  4. The function in the loop was print(i * i). Since i = 1, the result of i * i will be 1. a 1 is printed to the screen.
  5. The loop starts over again.
  6. The next element is taken and the second iteration of the loop begins. The first element of number is 5.
  7. i equals 5. Again print(i * i) is started and 25 is displayed.
  8. The loop will start again. The next element.
  9. One more element. This is the third iteration. The second element is 12.
  10. print(i * i) will print 144.
  11. The cycle restarts. The next element is present. This is a new iteration.
  12. The third element is 91. The value in the square is 8281.
  13. The cycle restarts. The next element is present. New iteration.
  14. i equals 102. The squared value is 10404.
  15. 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)

Итерация по объектам range() It takes three arguments: Как происходит итерация по объектам range()

  • 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: Итерация по объектам range с шагом 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:

  1. 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)
    
  2. 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 be my_list[i].

Either way, range() will make working with loops in Python easier.

Best Practices and Common Errors

  1. 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.
  2. 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.
  3. It is not allowed to print() strings and numbers with a + sign. This is more a peculiarity of the print 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: Нельзя выводить строки и числа в функции print 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])

Разбор цикла for — задача 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.

Related Posts

LEAVE A COMMENT