Last Updated:

Loop for Python - How it works?

In the Python programming language, there is a for loop that serves to iterate through the elements of data structures and other objects. In many languages, it is a loop with a counter, but not in this programming.

Let's try to figure out what is the search for elements. Suppose you have a list with a number of items. Going through the list, we take each of the elements in turn.

loop for python

It turns out that with each of the elements we perform the same action in the body for. Therefore, there is no need to think about which of the elements the list will end on, and retrieve the elements by indexes, because the for loop itself determines the end.

>>> spisok = [10, 40, 20, 30]
>>> for element in spisok:
... print(element + 2)
...
12
42
22
32

The variable element is used after the for keyword. You can use any name. The name i is often used. The next time the for loop is integrated, the following element from the spisok list will be used. The element identifier will be associated with the number 10 when scrolling first, with the second already with the number 40, and so on. After the elements are finished, the loop will finish its work.

When translated from English, "for" will mean "for", "in" as "in". In simple language, understandable for everyone, we can say this: for each element in the list, do the following (what is in the body of the loop).

For example, we increased each of the elements by 2 and displayed it on the screen. At the same time, the list remained unchanged:

>>> spisok
[10, 40, 20, 30]

Items were retrieved and used, but they were not overwritten. If you want to change the list itself, a variable is used that indicates the index of the item. For example, you want to change the value of each item in the list or just some, a specific condition:

>>> i = 0
>>> for element in spisok:
… spisok[i] = element + 2
… i += 1

>>> spisok
[12, 42, 22, 32]

If there is a need to use a counter, then there is no point in using a for loop. It is better to use the while, if of course the length of the list is known. If not, you can find it using the len() function in Python.

>>> i = 0
>>> while in < len(spisok): ... spisok[i] = spisok[i] + 2 # или spisok[i] += 2 ... i = i + 1 # или i += 1 ... >>> spisok
[14, 44, 24, 34]

Moreover, the while loop helped to get rid of the element variable.

Range() function

 

Next, we need to consider the range() function. "Range" can be translated as "range". It has the property of taking multiple arguments. Their purpose is the same as that of the randrange() function from the random module.

The generation of numbers from 0 to a certain number occurs if only one is specified. From the first to the second, without including it, are generated if two are specified. And accordingly, if three are given, then the third number will be considered a step. But, the main function range(), unlike randrange(), generates more than one number in the specified range.

 

In principle, it does not take random numbers into work, only a sequence of numbers. For example, range(5, 11) will generate a sequence 5, 6, 7, 8, 9, 10. But this is no longer a list data structure. These are objects of their class, namely the ranges:

>>> a = range(-10, 10)
>>> a
range(-10, 10)
>>> type(a)
<class ‘range’>

In the same case, the sequence of numbers is not reflected, it is possible to refer to its elements:

>>> a[0]
-10
>>> a[5]
-5
>>> a[15]
5
>>> a[-1]
9

Range() objects cannot be changed because they belong to the group of immutable, unlike lists:

>>> a[10] = 100
Traceback (most recent call last):
File «», line 1, in
TypeError: ‘range’ object does not support item assignment

Cycle for and range()

Together, the range() function and the for loop form a great pair, which is why you need to see them together.

Not to keep track of whether the end of the for structure has been reached and exists. The same cannot be said about while. In this case, the counter is not needed to modify and check the conditions in the header. However, in order to use the indexes of the elements of the same list, you need a range() that gives a sequence of integers.

>>> range(len(spisok))
range(0, 4)

Len will let us measure the length of the list. As you can see in the example , this is 4. Next, 4 will be passed to the range() function to generate a sequence of numbers from 0 to 3. Which is what the indexes of list items are.

Next, "connect" for and range():

>>> for i in range(len(spisok)):
… spisok[i] += 2

>>> spisok
[16, 46, 26, 36]

Elements are taken from the range object, in the title of the for loop. The list is not mentioned, the elements of this will be overwritten. When the length of the list is given, it will look like this: for i in range(4). How the I will be used in the body of the cycle is another matter.

Note! Instead of the identifier i, it may be used differently.

Enumerate() function

Just as often, another built-in function in Python is used in the header designated as for. Denoted as enumerate(). With range() allowing only indexes of elements to be detected, enumerate() can generate pairs that, in the situation under consideration, will consist of components such as the index of the element, as well as its immediate values.

>>> spisok = [16, 46, 26, 36]
>>> for i in enumerate(spisok):
… print(i)

(0, 16)
(1, 46)
(2, 26)
(3, 36)

It is possible to extract the index and value in the corresponding body in the structure of the cycle in question:

>>> for item in enumerate(spisok):
… print(item[0], item[1])

0 16
1 46
2 26
3 36

But still, two variables are usually used before in, most often in for headers:

>>> for id, val in enumerate(spisok):
… print(id, val)

0 16
1 46
2 26
3 36

What should I use range() in the for header? It's actually easier! If you don't need a value, you only need indexes.

One thing to remember is that the enumerate() function will return an iterator object. When generating these objects, the values cannot be recalculated a second time, they are empty.

To return the object and use the range function. It's not an iterator, but it can be brought to that. When used in the range() and enumerate() headers, these objects are lost because they are not assigned to variables and disappear at the end of the loop. But you can assign variables to them, then you get:

>>> r_obj = range(len(spisok))
>>> e_obj = enumerate(spisok)
>>> for i in r_obj:
… if i == 1:
… break

>>> for i in e_obj:
… if i[0] == 1:
… break

>>> for i in r_obj:
… print(i)

0
1
2
3
>>> for i in e_obj:
… print(i)

(2, 26)
(3, 36)

You need to stop retrieving items from an object on an item with an index of 1, then run the objects through a for loop. But it must be remembered that for r_obj the bypass begins again, and in case of e_obj will go with what he stopped.

However, the e_obj will not contain the items that were previously retrieved.

Iterators

An iterator is a data structure that is used to refer to a specific element, such as an object with a data flow. When the iterator is passed to the built-in next() method, it returns the next value from the associated data stream. A StopIteration exception is thrown when all elements are lost. And for any subsequent calls to the next() method, it will throw a StopIteration exception.

Integrators are also integrators, but they support, according to the iterator protocol, the inter() method by themselves. Therefore, you can get the iterator object itself by calling the inter() method.

Where integration is expected, you can use iterators, as in the for loop. But remember, after calling iter() for the container object, the new integrator will return each time. For the integrator, the call to inter() will return the same object.