Python arrays

by Alex
Python arrays

An array in Python is an ordered data structure used to store objects of the same type. In their functionality, they are similar to lists, but have some restrictions on the type of input data as well as its size. Despite this peculiarity, arrays are a fairly functional tool for working with datasets in the Python programming language.

Creating and Filling

Before you can add (create) a new array in Python 3, you must import the library responsible for working with such an object. To do this you will need to add the line from array import * to the program file. As it was said before, arrays are oriented to interact with one constant data type, consequently, all their cells have the same size. Using the array function, you can create a new data set. This example demonstrates how to fill a Python array by writing integers using the method above.

from array import *
data = array('i', [2, 5, 4, 0, 8])

As you can see, the array function takes two arguments, the first of which is the type of the array being created, while the second is an initial list of its values. In this case i is a signed integer that takes up 2 bytes of memory. Other primitives can be used instead, such as a 1-byte character (c) or a 4-byte floating-point number (f).

It is important to remember that the array can only store data of one type, otherwise a program call will end with an error.

To access an element, use square brackets, e.g., data[2].

Adding an element

To add a new element to the Python array, you must use the insert method. To do this, you need to call it through the object you created earlier and enter two values as arguments. The first (4) is the index of the new element in the array, that is, where it should be placed, and the second (3) is the value itself.

from array import *
data = array('i', [2, 5, 4, 0, 8])
data.insert(4, 3)

Remember that you can only add data of the type that the earlier created object refers to. When you perform an operation like that, the number of available cells increases according to the current needs of the program.

Deleting an element

In Python, you can remove unneeded elements from an array using the pop method, which has the cell index as its argument (3). As with adding a new element, the method must be called through a previously created object, as shown in the example.

from array import *
data = array('i', [2, 5, 4, 0, 8])
data.pop(3)

After performing this operation, the contents of the array are shifted so that the number of available memory cells is the same as the current number of elements.

Output

When you work with any data in your program, from time to time it becomes necessary to check it, and you can easily do it by displaying it on the screen. The function print will help you with that. It takes an element of a previously created and filled array as an argument. In the following example, it is processed through a for loop, where each element of the array data receives a temporary identifier i to be passed to the method print, mentioned above.

from array import *
data = array('i', [2, 5, 4, 0, 8])
for i in data:
    print(i)

The result of the above code is the output of the Python array – going through all of the previously assigned integer values and outputting them one column at a time.

Obtaining Size

Since the size of an array can change during the execution of a program, it is sometimes useful to know the current number of elements in the array. The len function is used to get the length (size) of an array in Python as an integer value. To display the number of elements of an array on the screen in Python, use the print method.

from array import *
data = array('i', [2, 5, 4, 0, 8])
print(len(data))

As you can see from the above code, the function print takes as its argument the result of len, so that it can print the numerical value into the console.

A two-dimensional array

In some cases, an ordinary one-dimensional array is not enough to correctly represent a particular set of information. In the Python 3 programming language there are no two-dimensional and multidimensional arrays, but the basic capabilities of this platform can easily build a two-dimensional list. Elements of such a construct are arranged in columns and rows, filled in as shown in the following example.

d1 = []
for j in range(5):
    d2 = []
    for i in range(5):
        d2.append(0)
    d1.append(d2)

Here you can see that the basic idea behind implementing a two-dimensional dataset is to create multiple lists d2 inside one big list d1. Two for loops are used to automatically fill a 5×5 matrix with zeroes. The append and range methods help with this task, the first of which adds a new element to the list (0), and the second allows you to set its value (5). It is worth noting that for each new cycle for uses its own temporary variable, which performs the representation of the current element of the external (j) or internal (i) lists. You can refer to the desired cell of a multidimensional list by specifying its coordinates in square brackets, oriented by rows and columns: d1[1][2].

Multidimensional array

As in case of a two-dimensional array represented as a complex list, the multidimensional array is implemented according to the principle of “lists within a list”. The following example clearly demonstrates the creation of a three-dimensional list that is filled with null elements using three for loops. Thus, the program creates a matrix of dimension 5×5×5.

d1 = []
for k in range(5):
    d2 = []
    for j in range(5):
        d3 = []
        for i in range(5):
            d3.append(0)
        d2.append(d3)
    d1.append(d3)

Similar to a two-dimensional array, you can refer to the cell of the constructed object above using indices in square brackets, such as d1[4][2][3].

Conclusion

Arrays are generally used in the Python programming language to interact with datasets of the same type. The standard platform library allows you to work with such a structure quite effectively, providing the ability to manipulate its contents using appropriate functions. In addition, Python supports multidimensional representation of lists with no limit on the number of levels.

Related Posts

LEAVE A COMMENT