Working with array elements
Much of the usefulness of arrays comes from the fact that its elements can be accessed individually.
The way to do this is to use an index to number the elements.
Indexis a value that points to a specific array element.
To refer to an element of an array, you must specify the name of the array followed by its index in square brackets. For example, you can write the value 100 to the array element at index 1 like this: A[1] = 100
.
You have to remember!
NUMBERING ARRAYS IN PYTHON STARTS FROM ZERO!
(This is a prerequisite - you must start from scratch. This is especially important to remember.)
Example
x = (A[3] + 5) * A[1] # read the values of A[3] and A[1]
A[0] = x + 6 # write new value to A[0]
Let's analyze the program for working with array elements.
i = 1
A = [0] * 5 # create an array of 5 elements
A[0] = 23 # into each of the 5 array elements (indexes 0 to 4)
A[1] = 12 # write a specific value
A[2] = 7
A[3] = 43
A[4] = 51
A[2] = A[i] + 2*A[i-1] + A[2*i] # change the value of the element with index 2 to the result of the expression
# since i=1, then substituting the value of the variable i into the expression we get
# the following expression A[2] = A[1] + 2*A[0] + A[2];
print(A[2] + A[4])
As a result of running this program the value of the sum of the elements of the array with index 2 and with index 4 equal to 116 will appear on the screen. As you can see from the example, we can access any element of the array. And also calculate the required element number using various formulas (for example, as in the program A[i-1]
or A[2*i]
). In these cases, the indexes of the elements will be calculated and depend on the value of i.
In Python, you can use negative index values for arrays, and count from the end of the array. For example:
A[-1] - the last element of the array
A[-2] - penultimate element
etc.
Let's analyze the program.
N=5
A = [0] * N
x=1
print(A[x - 3]) # accessing element A[-2]
print(A[x - 3 + len(A)]) # access element A[3]
# this is the same element as A[-2]
A[x + 4] = A[x] + A[2 * (x + 1)] # after substituting x into expressions and calculations
# get the next line A[5] = A[1] + A[4]
# A[5] no such element exists
# error - out of bounds array
Since the array is declared with 5 elements, the elements will be numbered from -5
to 4
. We see that the program in the 6th line refers to a non-existent element: A[5]
.
It turns out that the program has gone beyond the bounds of the array.
In such cases, the program usually crashes with
run-time error.