Iterating over array elements
When working with arrays, you usually have to work with all the elements of the array at once.
Iterate through elements: loop through all the elements of the array and, if necessary, perform some operation on each of them.
For this, a loop with a variable is most often used, which changes from
0
to
N-1
, where
N
is the number of array elements.
Under
N
we will consider the current size of the array, i.e.
N = len(A).
...
for i in range(N):
# here we work with A[i]
...
In the specified loop, the variable i
will take the values 0, 1, 2, ..., N-1. Thus, at each step of the loop, we access a specific element of the array with the number i
.
Thus, it is enough to describe what needs to be done with one element of the A[i]
array and place these actions inside such a loop.
Let's write a program that fills the array with the first N
natural numbers, that is, at the end of the program, the elements of the array should become equal
A[0] = 1
A[1] = 2
A[2] = 3
...
A[N - 1] = N
It is easy to see the pattern: the value of an array element must be greater by 1 than the index of the element.
The loop will look like this
for i in range(N):
A[i] = i + 1