The Python array cheatsheet

The Python array cheatsheet

Lists and arrays are two essential elements of Python development. In order to guarantee good maintainability and correct data processing, several methods are provided natively by the language.

In this article, we’ll take a look at a non-exhaustive list of the most useful methods for processing arrays in Python.

At the end of the article, you’ll also find a download link to a PDF cheatsheet listing all the tips and tricks highlighted in this article.

The basics of manipulating a list in Python.

Creating a list in python.

Build a list of elements with no elements initially added:

list = []

Build a list of elements by integrating elements beforehand:

list = [1, 3, 6, 9]

Emptying a list in python.

Delete all the elements in a list in Python using the clear() method:

list = [1, 3, 6, 9]
list.clear() // []

Adding and deleting items in a list in python.

Add an element to the end of a list in Python using the .append() method:

list = [1, 3, 6, 9]
list.append(11) // [1, 3, 6, 9, 11]

Add an element to the beginning of a list in Python using the .insert() method:

list = [1, 3, 6, 9]
list.insert(11) // [11, 1, 3, 6, 9]

Add an element just before the position given as an argument using the .insert() method:

list = [1, 3, 6, 9]
list.insert(11, 2) // [1, 3, 11, 6, 9]

Deleting an element from a list in Python using the .remove() method:

list = [1, 3, 6, 9]
list.remove(3) // [1, 6, 9]

Deleting an element from a list in Python using del indexing:

list = [1, 3, 6, 9]
del list[0] // [3, 6, 9]

Add items from another list to a list in Python using the .fromlist() method:

list = [1, 3, 6, 9]
list2 = [11, 13, 16, 19]
list.fromlist(list2) // [1, 3, 6, 9, 11, 13, 16, 19]
list = [1, 3, 6, 9]
list.pop(1) // [1, 6, 9]

Delete an element in a specific index in a list in Python using the .pop() method:

The pop method returns the number of elements remaining in the python list.

Make a copy of a list in Python using the .copy() method:

list = [1, 3, 6, 9]
list2 = list.copy() // [1, 3, 6, 9]

Retrieving specific items from a list in python.

Find the size of a list in Python using the .len() function:

list = [1, 3, 6, 9]
len(list) // 4

Retrieving an element using its index in a list in Python:

list = [1, 3, 6, 9]
list[0] // 1

Retrieve all elements from a specific index in a list in python:

list = [1, 3, 6, 9]
list[1:] // [3, 6, 9]

Retrieve all elements in an interval between two index arguments in a python list:

list = [1, 3, 6, 9]
lis[1:3] // [3, 6]

Retrieve all elements before an argument index in a list in python:

list = [1, 3, 6, 9]
lis[:3] // [1, 3, 6]

Get the number of occurrences of a value in a list in Python using the .count() method:

list = [1, 3, 6, 3, 9]
list.count(3) // 2

Get the largest element of a list in python using the max() function:

list = [1, 3, 6, 9]
max(list) // 9

Get the smallest element of a list in python with the min() function:

list = [1, 3, 6, 9]
min(list) // 1

Check whether a python list is larger than another python list using the cmp() function:

list1 = [1, 3, 6, 9]
list2 = [11, 13, 16, 19]
cmp(list1, list2) // -1
cmp(list2, list1) // 1
cmp(list1, list1) // 0

Get the sum of the elements in a list in Python using the sum() function:

list1 = [1, 3, 6, 9]
sum(list1) // 19

Validating the presence of items in a list in Python.

Check that the values in a Boolean list are all True using the all() function:

list1 = [True, True, True]
list2 = [True, False, True]
all(list1) // True
all(list2) // False

Check that at least one of the values in a Boolean list is true using the any() function:

list1 = [True, False, False]
any(list1) // True

Handling lists in Python.

Transforming a list in python.

Add a list to another list in Python using the .extend() method:

list = [1, 3, 6, 9]
list2 = [11, 13, 16, 19]
list.extend(list2) // [1, 3, 6, 9, 11, 13, 16, 19]
list = [1, 3, 6, 9]
list.reverse() // [9, 6, 3, 1]

Reverse the order of a list in Python using the reverse() method:

Sort lists in Python.

Sort list in python in ascending order using the sorted() function:

list = [3, 1, 9, 6]
sorted(list) // [1, 3, 6, 9]
list = [3, 1, 9, 6]
sorted(list, reverse=True) // [9, 6, 3, 1]

An alternative with an additional argument is to sort lists in python in descending order using the sorted() function:

Transforming and converting a list in Python.

Transform a list in python into a string variable using the str() function:

list = [1, 3, 6, 9]
str(list) // “[1, 3, 6, 9]

Browse a list with loops:

Perform an action for any element in a list in Python using a for loop:

list = [1, 3, 6, 9]
for el in list:
	el = 0

Perform an action for any element in a list in Python with a while condition:


while i < len(list):
	list[i] = 0
	i ++

The difference between lists and arrays in Python.

Python offers different ways of storing data. Lists and arrays are two of them, and each has its advantages and disadvantages. Before presenting the tips for handling arrays, here is a short description of the differences between arrays and lists.

The three main differences between lists and tables.

The first distinction is that a list can have elements of several types, whereas an array will be typed.

To use arrays in Python, you need to have the numpy package installed, whereas lists are natively present in the language.

An array must be declared before use, whereas a list must not.

How do I choose between a list and an array in Python?

Choose tables:

It’s better to use arrays if you need a lot of storage space.

Arrays are more flexible for algebraic operations and manipulation.

Tables are lighter in terms of memory size and should therefore be used where necessary.

Choose the lists:

Nested arrays must have the same dimension, but lists do not. This gives absolute freedom when it comes to the dimensions of nested objects.

A list will be faster and lighter when stored without processing.

The list is easier to present because it doesn’t need a loop to present its contents.

The basics of manipulating a 2d array in python.

Creating an 2d array in python.

Construct a 2d array in python elements beforehand using numpy.array():

import numpy as np
array = np.array([1, 3, 6, 9])

Retrieving specific elements from a 2d array in python.

Retrieving an element using its index in a python array:

import numpy as np
array = np.array([1, 3, 6, 9])
array[1] // 3

Retrieve all elements from a specific index in a python array:

import numpy as np
array = np.array([1, 3, 6, 9])
array[1:] // [3, 6, 9]

Retrieve all the elements in an interval between two argument indexes in a python array:

import numpy as np
array = np.array([1, 3, 6, 9])
array[1:3] // [3, 6]

Retrieve all elements before an argument index in a 2d array in python:

import numpy as np
array = np.array([1, 3, 6, 9])
array[:3] // [1, 3, 6]

Retrieve the data type present in an array in Python using the .dtype() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array.dtype // int64

Retrieve the dimension of a python array and the dimensions of nested elements using .shape:

import numpy as np
array = np.array([[1, 3, 6, 9], [11, 13, 16, 19]])
array.shape // (2, 4)

Find the indices linked to a value in a python array using the .where() method:

import numpy as np
array = np.array([1, 3, 6, 3])
np.where(array == 3) // [1, 3]

Find the index in which to insert a value to maintain the established order in a python array using the .searchsorted() method:

import numpy as np
array = np.array([1, 3, 6, 3])
np.searchsorted(array, 2) // 1

Handling arrays in Python.

Transforming an array in python.

Make a copy of a python array by creating a new array using the .copy() method:

import numpy as np
array = np.array([1, 3, 6, 9])
arrayCopy = array.copy() // [1, 3, 6, 9]

An alternative is to make an inseparable copy of the first array using the .view() method:

import numpy as np
array = np.array([1, 3, 6, 9])
arrayCopy = array.view() // [1, 3, 6, 9]

When using .view(), if the reference array changes, the second array will also change, which is not the case with .copy().

Transform a python array by nesting the values into a defined number of objects of a specific size using the .reshape() method:

import numpy as np
array = np.array([1, 3, 6, 9, 11, 13, 16, 19])
array.reshape(2, 4) // [[1, 3, 6, 9], [11, 13, 16, 19]]

Merge two python arrays using the .concatenate() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array2 = np.array([11, 13, 16, 19])
arrayResult = np.concatenate(array, array2) // [1, 3, 6, 9, 11, 13, 16, 19]

Alternatively, you can merge two Python arrays using an axis defined using the .stack() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array2 = np.array([11, 13, 16, 19])
arrayResult = np.stack((array, array2), axis=1) // [[1, 11], [3, 13], [6, 16], [9, 19]]

Merge two python arrays of nested elements inline with the .hstack() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array2 = np.array([11, 13, 16, 19])
arrayResult = np.hstack((array, array2)) // [1, 3, 6, 9, 11, 13, 16, 19]

Merge two python arrays, keeping the arrays as nested elements using the .vstack() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array2 = np.array([11, 13, 16, 19])
arrayResult = np.vstack((array, array2)) // [[1, 3, 6, 9], [11, 13, 16, 19]]

Merge two columnar python arrays using the .dstack() method:

import numpy as np
array = np.array([1, 3, 6, 9])
array2 = np.array([11, 13, 16, 19])
arrayResult = np.dstack((array, array2)) // [[1, 11], [3, 13], [6, 16], [9, 19]]
import numpy as np
array = np.array([1, 3, 6, 9, 11, 13, 16, 19])
arrayResult = np.array_split(array, 4) // [[1, 3, 6, 9], [11, 13, 16, 19]]

Split a Python array into nested elements of a defined dimension using the .array_split() method:

Sorting the elements of an array in Python.

Sort the elements of a python array in ascending order using the .sort() method:

import numpy as np
array = np.array([3, 1, 9, 6])
np.sort(array) // [1, 3, 6, 9]

When using an array of nested elements, the .sort() method will preserve the nesting and sort the nested elements separately.

Browse a python array with loops:

Perform an action for any element in a python array with a for loop:

import numpy as np
array = np.array([1, 3, 6, 9])
for var in array:
	print(var)
Photo Maxime Macé

Maxime Macé

Simple passionné de thématiques diverses et variées. J’apprécie enrichir mes connaissances dans les disciplines techniques comme l’informatique, les sciences et l’ingénierie, mais aussi dans les domaines merveilleux de la philosophie, l’art et la littérature.

Prenons contact

Vous souhaitez me contacter suite à la lecture de cet article ? Merci de renseigner votre adresse électronique et je vous recontacterai dans les plus brefs délais.

CV Ingénieur développeur informatique

CV Étudiant PhD Artificial Intelligence

Portfolio Artist designer