Array in "Python" (Python)

Table of contents:

Array in "Python" (Python)
Array in "Python" (Python)

Python is a high-level general purpose programming language. Supports not only OOP, but also structural, functional, imperative, aspect-oriented programming. The standard library contains many tools for working with network protocols, text encodings, multimedia formats, and for developing cross-platform applications.

Array in "Python"

A one-dimensional array is a list of elements.

Arrays in Python
Arrays in Python

List values are indicated between square brackets [], separated by commas. Any element is called by index. Elements can be assigned new values.

This is what an empty list looks like:


An array of strings in "Python" looks like this:

  • Prime=['string1', 'string2', 'string3']
  • Prime[1]='string2'; //true

The len() function returns the number of elements inside the list.

len(Prime)==4; // true

The for loop is used to enumerate array elements. Its difference from Pascal is that it iterates over the elements, not their indices.

for elemin [1, 4, 67]

To create a cycle, a generator for filling lists is used. Written as [array value for variable name in number of elements];

A two-dimensional array in "Python" is created using nested generators. It should look something like this:

[[0 for j in range(m)] for i in range(n)]

Creating an array in NumPy

To create and modify arrays in Python, the NumPy library is used.

JAP Python
JAP Python

It supports multidimensional array and matrices, has a large set of packages for solving mathematical problems. It also provides work with homogeneous multidimensional arrays and matrices. To be able to use the functions of this package, you need to import it.

import numpy as np

One of the easiest ways to define an array in Python is to use the array() function. It creates an object of type ndarray.

array=np.array(/ set of elements /)

Array is now of type ndarray. This can be checked with the array.type() function. It took as an argument the name of the created array. The answer will be returned -.

To override a type, use dtype=np.complex at creation time.

array2=np.array([/elements/, dtype=np.complex)

If you need to specify an array, but its elements are unknown at this stage, it is filled with zeros by the zeros() function. You can create an array of units with the ones() function. The number of nestedarrays and the number of elements inside.

np.zeros(2, 2, 2)

Creates two arrays inside that contain 2 elements each.

  • array([
  • [[0, 0]]
  • [[0, 0]]]
  • )

To display an array on the screen, use the print() function. If the array is too large to print, NumPy hides the central part and prints only the extreme values.

To see the entire array, use the set_printoptions() function. By default, only the first 1000 items are displayed. This value is specified as an argument with the threshold keyword.

Basic NumPy operations

Any actions on array elements in "Python" involve the creation of a new array.

NumPy library
NumPy library

The created array contains elements obtained as a result of performing some actions on them. Arrays can only interact if they are the same size. For example:

  • array1=np.array([[1, 2, 3], [1, 2, 3]])
  • array2=np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

When executing array1 + array2, the compiler will throw an error because the size of the first array is 2 and the second is 3.

  • array1=np.array([1, 2, 5, 7])
  • array2=arange([1, 5, 1])

Array1 + array2 will return an array with elements 2, 4, 8, 11. No error will occur because both are the same size.

Instead of manual addition, you can use the function that is included in the ndarray sum() class.

np.array(array1 + array1)==array1 +array2

The ndarray class provides a large library of methods for mathematical operations. They are specified as np.method name (variable name).


The size of an array in "Python" determines the shape. The shape() method is used to check the current shape.

One-dimensional, two-dimensional and three-dimensional array
One-dimensional, two-dimensional and three-dimensional array

An array with two and three elements has the form (2, 2, 3). It will change if shape() is given arguments. The number of subarrays will be used as the first one, the dimension of each subarray will be used as the second one. The same operation is performed by the reshape() function. Its parameters determine the number of rows and columns.

There are methods to manipulate the form. For example, ravel() converts a multidimensional array into a one-dimensional array by building the internal values in ascending order. The transpose() function swaps the rows and columns of a multidimensional array.


Often you have to work not with the whole array, but only with some of its elements. For these purposes, in "Python" there is a method "Slice" (slice). He came to replace the iteration of elements with the for loop.

Slicing in Python
Slicing in Python

The method opens up wide possibilities for getting a copy of an array in "Python". All manipulations are carried out in this form [start:stop:step]. Here, the start value denotes the index of the element from which the countdown starts, the stop value is the last element, the step size is the number of elements to skip during each iteration. By default, start is zero, that is, the countstarts from the zero element of the list, stop is equal to the index of the last element in the list, the step is equal to one, that is, iterates over each one in turn. If passed to a function with no arguments, the list is copied in its entirety from beginning to end.

For example, we have an array:

mas=[1, 2, 3, 4]

To copy it, use mas[:]. The function will return the sequence of elements [1, 2, 3, 4]. If the argument is a negative value, such as -3, the function will return elements with indexes from the third to the last.

mas[-3]; //[4]

After the double colon, the step of the elements copied in the array is indicated. For example, mas[::2] will return an array [1, 3]. If a negative value is specified, for example, [::-2] the count will start from the end, and we get [3, 1].

The slice method can flexibly work with nested lists. For a two-dimensional array in Python, [:, 2] means that every third element of all arrays will be returned. If you specify [:2] - the first two will be returned.


Getting a copy is done using the slices described above. Copying by assignment doesn't work in Python because it doesn't transfer the objects themselves, but only the references. This means that by creating an array with the values of np.arange(10) and assigning array2=array1, we get two objects with the same values but different names, in this case array1 and array2. Changing the shape of one of them will affect the second. The function array1.shape(3, 4) will reshape array2.

  • array1.shape()==(3, 4);//true
  • array2.shape()==(3, 4);//true

The view() function creates different objects with the same data. For example, we have an array array to which we apply the view() function


Assign the resulting value to the second array array2 and see that these are different objects, but they have the same data. Checking:

array2 is array1; //false

If we change the shape of one of the arrays, it does not change in the second.

  • array1.shape(2, 6)
  • array1==array2; // true

Merge, split

Arrays can be combined with each other. This is done along axes or rows. The hstack() function concatenates them by rows, while vstack() concatenates them by columns.

Using the column_stack() function, you can combine arrays in arguments into one one-dimensional array. Similar to column_stack() row_stack() works, but concatenates rows, not columns. To split an array horizontally, use the hsplit() function, and vsplit() vertically.

Popular topic

Editor's choice

  • IPv6 protocol: setup on Windows systems
    IPv6 protocol: setup on Windows systems

    Probably, many users of computer systems, delving into the network settings, noticed that in the list of protocols, in addition to the well-known IPv4, there is also the sixth version (IPv6)

  • View history on computer
    View history on computer

    Today you can learn about almost all the actions taken on the computer. It's about browsing history

  • Computer technology hardware: definition, description and types
    Computer technology hardware: definition, description and types

    Modern computers to ensure maximum performance and correct operation use hardware and software that are very interconnected and clearly interact in different directions. Now let's touch on the consideration of hardware, since initially it is they who occupy a dominant position in ensuring the operability of any computer or even mobile system

  • Keyboard shortcuts and the evolution of operating systems
    Keyboard shortcuts and the evolution of operating systems

    It takes about a minute to copy or move a file from one location to another using the menu system. The developers introduced a keyboard shortcut that replaced all these actions and made it possible to reduce the time of this common operation by 3 or more times. True, for this it was necessary to slightly modernize the keyboard: new keys were added - "Ctrl", and later - "Windows"

  • If the torrent does not download
    If the torrent does not download

    An article for those who consider the ability to download files from torrent trackers a convenience, not an echo of the past. Not only the unavailability of "high-speed" tariff plans is the reason for the choice, but also personal preferences