Data storage

Let's say you've developed a computer game called "User Hostile" in which the players compete against an intricate and unfriendly computer interface. Now you need to write a program that tracks the monthly sales of this game over a five year period. Or let's say you need to inventory Hacker Hero Trading Cards.
Very soon you will come to the conclusion that you need more than simple basic data types to store and process information.
 

Lists (arrays)

In order to make it convenient to work with a large amount of data, a group of cells is given a common name. Such a group of cells is called an array.
 
Array – it is a group of memory cells of the same type, located side by side and having a common name. Each cell in the group has a unique number.

When working with arrays, you need to learn how to solve three tasks:
x allocate memory of the required size for the array;
x write data to the desired cell;
x read data from a cell.

 

Arrays in Python

There are no such arrays in Python. Instead, lists are used to store a group of objects of the same type (but not only of the same type) - objects of the list type. The difference between lists and arrays is that a list is a dynamic structure, the size of which can be changed during program execution (deleting, adding elements) without thinking about memory management operations (this is done by the compiler).
In the future, when analyzing work with lists, we will use the word "array", since most often lists are used precisely in the role of an array (they store data of the same type).
 
Creating an array
When an array is created, space is allocated in memory (a certain number of cells). 1) Arrays can be created by simply enumerating elements: A = [1, 4, 7, 12, 5] print(type(A)) The program will output
<class 'list'>
That is, an array is an object of type list (translated from English list).

2) Arrays can be composed of data of any type - integers or real numbers, character strings  A = ["Vasya", "Petya", "Fedya"]

Some ways to work with arrays
3) Arrays can be "added". A = [1, 5] + [25, 7]
4) Addition of identical arrays can be replaced by multiplication. So it's easy to create an array filled with the same values, like so: A = [0]*10 # created an array of 10 elements and filled it with zeros
5) An array always "knows" your size. The  len() function is used to determine the size of an array. Often the size of the array is stored in a separate variable so that the program can be easily changed to work with a different array size.

Example
N = 10 # store the size of the array in variable N A = [0] * N # create an array of size N print(len(A)) # print the size of the array The size of an array can be set from the keyboard.

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.

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

List generators

The Python language allows you to solve many problems concisely and reliably. Let's list the main possibilities for filling an array. 1) Creating and populating an array can be written like this: A = [i for i in range(N)] # With N = 5, array A = [0,1,2,3,4] A = [i*i for i in range(N)] # With N = 5, array A = [0,1,4,9,16] for i in range(N) - loops through all i values ​​from 0 to N-1.

The next element of the array will contain the value that comes before the word for, in the first case i, in the second - i*i.

We get the same result using the following notation:
A = list(range(N)) # with N = 5, array A = [0,1,2,3,4]

2) You can write to the array not all values, but only those that satisfy a certain condition.
 
Example
Filling the array with all even numbers in the range 0 to 9. A = [i for i in range(10) if i % 2 == 0] print(*A) # array A = [0,2,4,6,8] In this case, you need to understand that the length of the array will be less than 10. 

3) Filling an array from the keyboard with elements that are located one per line can be done in two ways.
 
N=5 A = [0]*5 for i in range(N): A[i] = int(input())
A = [int(input()) for i in range(N)]
# each time the loop repeats,
# the input string is converted
# to an integer (using int)
# and this number is added to the array


4) Filling an array from the keyboard with elements that are all located on the same line is a bit more complicated. You need to read the string, split it into elements, and then convert each element to an integer s = input().split()  A = [int(i) for i in s]  or so A = list(map(int, input().split())) # built-in function list()   # transforms the sequence   # to mutable list

Array output

You can also display an array on the screen in different ways.
 
Standard way, used in many programming languages. Such a cycle can be written shorter. The value of х at each step of the loop is filled with the next element of the array. In Python, you can write like this.
for i in range(len(A)): print(A[i], end=" ") for x in A: print(x, end=" ")
print(*A)
# sign * in front of the name
# of the array means that
# needs to be converted
# array into a set of individual values