Iteration on lists of elements
In the previous sections we introduced lists that are composed of a sequence of elements. Often it is necessary to perform operations on these lists, element by element, in an iterative form.
We have seen that iterations can be coded using the WHILE construct.
So for example if after creating a list we want to multiply each of its elements by two we can write the following code.
lista = [0,1,2,3,4,5,6]
lista2 = []
i = 0
n = len(lista) - 1
while i < n:
lista2.append(lista[i]*2)
i += 1
print(lista2)
In doing so we will obtain the list with each element doubled in value.
>>>
[0, 2, 4, 6, 8, 10, 6]
The FOR-IN construct
However, despite the correctness of the previous code, from the point of view of coding and legibility many lines of code are required to express what then is a simple concept: iteration for every element in the list. In fact we had to create a counter, manage the increase, count the elements contained in the list and create a condition for iteration.
Well all these operations can be expressed with a simple FOR-IN construct, which requires only one line
lista = [0,1,2,3,4,5,6]
lista2 = []
for item in lista:
lista2.append(item*2)
print(lista2)
As you can see, each element of the list array is copied into a temporary variable called item, on which you will work within the FOR loop by writing a series of commands to the indentation. No need for counters, you do not need to know how long the list is.
Perform a series of operations a number of times
Sometimes, however, we need to execute a set of operations a well-defined number of times. In this case there is no condition to check, but only the number n of times to repeat the cycle. In this case too, the WHILE loop could be used infinitely with a counter that takes into account the times a series of commands are executed. But here too the FOR-IN construct proposes itself as more efficient.
Using the range () function that returns a list of an ordered sequence of values ranging from 0 to n. We can write example:
>>> for i in range(5):
print("Execution")
>>>
Execution
Execution
Execution
Execution
Execution
In this way I managed to repeat the print 5 times.
⇐ Go to Python Lesson 2.10 – The range function()
Go to Python Lesson 3.1 – Functions and modules – code reuse ⇒