English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Matrix and NumPy Array

In this article, we will learn how to use nested lists and the NumPy package for Python matrices.

A matrix is a two-dimensional data structure where numbers are arranged in rows and columns. For example:

This matrix is3x4("3x4") matrix, as it has3rows4columns.

Python matrix

Python does not have a built-in matrix type. However, we can view lists of lists as matrices. For example:

A = [[1, 4, 5], 
    [-5, 8, 9]]

We can view this list of lists as having2rows3matrix columns.

Before continuing with this article, make sure you understandPython lists.

Let's see how to use nested lists.

A = [[1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19]]
print("A =", A) 
print("A[1="", A[1]) # the second row
print("A[1][2="", A[1][2]) # the third element of the second row
print("A[0][-1] = ", A[0][-1]) # the last element of the first row
column = []; # empty list
for row in A:
  column.append(row[2])   
print("3rd column =", column)

When we run the program, the output will be:

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]
A[1] = [-5, 8, 9, 0]
A[1][2="", 9
A[0][-1="", 12
3rd column = [5, 9, 11]

The following are some examples related to Python matrices using nested lists.

Using nested lists as matrices can be used for simple computational tasks, but usingNumPyis a better way to handle matrices in Python.

NumPy array

NumPy is a software package for scientific computing that supports powerful N-dimensional array objects. Before using NumPy, you need to install it. For more information,

Once NumPy is installed, you can import and use it.

NumPy provides multi-dimensional arrays of numbers (which is actually an object). Let's take an example:

import numpy as np
a = np.array([1, 2, 3])
print(a)                  # Output: [1, 2, 3]
print(type(a))            # Output: <class 'numpy.ndarray'>

As you can see, NumPy's array class is called ndarray.

How to create a NumPy array?

There are several ways to create a NumPy array.

1. Integer, floating-point and complex arrays

import numpy as np
A = np.array([1, 2, 3], [3, 4, 5])
print(A)
A = np.array([1.1, 2, 3], [3, 4, 5])  # Floating-point array
print(A)
A = np.array([1, 2, 3], [3, 4, 5], dtype = complex)  # Complex array
print(A)

When running the program, the output is:

[[1 2 3]
 [3 4 5]]
[[1.1 2.  3. ]]
 [3.  4.  5. ]]
[[1.+0.j 2.+0.j 3.+0.j]
 [3.+0.j 4.+0.j 5.+0.j]]

2. array of zeros and ones

import numpy as np
zeors_array = np.zeros((2, 3) )
print(zeors_array)
'''
 Output:
 [[0. 0. 0.]
  [0. 0. 0.]]
'''
ones_array = np.ones((1, 5), dtype=np.int32 ) // dtype
print(ones_array)          # Output: [[1 1 1 1 1]]

Here, we specify dtype32bit (4bytes). Therefore, the array can take values from to.-2-312-31-1

3. using arange() and shape()

import numpy as np
A = np.arange(4)
print('A =', A)
B = np.arange(12).reshape(2, 6)
print('B =', B)
''' 
Output:
A = [0 1 2 3]
B = [[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
'''

Learn aboutCreating a NumPy arrayMore information on other methods.

matrix operations

Above, we provided3For example: addition of two matrices, multiplication of two matrices, and transpose of one matrix. Before writing these programs, we used nested lists. Let's see how to accomplish the same task using NumPy arrays.

Addition of two matrices

We use+operator adds corresponding elements of two NumPy matrices.

import numpy as np
A = np.array([2, 4], [5, -6])
B = np.array([9, -3], [3, 6])
C = A + B  # Element-wise addition
print(C)
''' 
Output:
[[11  1]
 [ 8  0]]
 '''

multiplying two matrices

To multiply two matrices, we use the dot() method. Learn more aboutnumpy.dotMore information on how it works.

Note: *Used for array multiplication (multiplication of corresponding elements of two arrays), not matrix multiplication.

import numpy as np
A = np.array([3, 6, 7], [5, -3, 0]])
B = np.array([1, 1], [2, 1], [3, -3])
C = A.dot(B)
print(C)
''' 
Output:
[[ 36 -12]
 [ -1   2]]
'''

matrix transpose

We usenumpy.transposeCompute the transpose of the matrix.

import numpy as np
A = np.array([1, 1], [2, 1], [3, -3])
print(A.transpose())
''' 
Output:
[[ 1  2  3]
 [ 1  1 -3]]
'''

As you can see, NumPy makes our task easier.

Accessing matrix elements, row and column

Accessing matrix elements

Similar to lists, we can use indexing to access elements of a matrix. Let's start with one-dimensional NumPy arrays.

import numpy as np
A = np.array([2, 4, 6, 8, 10])
print("A[0] =", A[0])  # First element     
print("A[2="", A[2"]  # Third element 
print("A[-1="", A[-1"]  # Last element

When running the program, the output is:

A[0] = 2
A[2="", 6
A[-1="", 10

Now, let's see how to access elements of a two-dimensional array (basically a matrix).

import numpy as np
A = np.array([1, 4, 5, 12],
    [-5, 8, 9, 0],
    [-6, 7, 11, 19])
# First element of first row
print("A[0][0] =", A[0][0])  
# Third element of second row
print("A[1][2="", A[1][2])
# Last element of last row
print("A[-1][-1="", A[-1][-1])

When we run the program, the output will be:

A[0][0] = 1
A[1][2="", 9
A[-1][-1="", 19

Accessing the rows of the matrix

import numpy as np
A = np.array([1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19])
print("A[0] =", A[0])  # First Row
print("A[2="", A[2"]  # Third Row
print("A[-1="", A[-1"]  # Last Row (3rd row in this case)

When we run the program, the output will be:

A[0] = [1, 4, 5, 12]
A[2] = [-6, 7, 11, 19]
A[-1] = [-6, 7, 11, 19]

Accessing the columns of the matrix

import numpy as np
A = np.array([1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19])
print("A[:,0] =", A[:,0])  # First Column
print("A[:,3="", A[:,3"]  # Fourth Column
print("A[:,-1="", A[:,-1]) # Last Column (4th column in this case)

When we run the program, the output will be:

A[:,0] = [ 1 -5 -6]
A[:,3] = [12  0 19]
A[:,-1] = [12  0 19]

If you do not understand how the above code works, please read the slicing section of this article on matrices.

Matrix Slicing

One-dimensional NumPy array slicing is similar to lists. If you are not familiar with how list slicing works, please visitUnderstand Python's slicing notation.

Let's take an example:

import numpy as np
letters = np.array([1, 3, 5, 7, 9, 7, 5])
# 3rd to 5th elements
print(letters[2:5]) # Output:5, 7, 9]
# 1st to 4th elements
print(letters[:-5]) # Output:1, 3]   
# 6th to last elements
print(letters[5:]) # Output: [7, 5]
# 1st to last elements
print(letters[:]) # Output: [1, 3, 5, 7, 9, 7, 5]
# Reversing a list
print(letters[::-1)] # Output: [5, 7, 9, 7, 5, 3, 1]

Now, let's see how to slice a matrix.

import numpy as np
A = np.array([1, 4, 5, 12, 14], 
    [-5, 8, 9, 0, 17],
    [-6, 7, 11, 19, 21])
print(A[:2, :4)] # Two rows, four columns
''' Output:
[[ 1  4  5 12]
 [-5  8  9  0]]
'''
print(A[:1,]) # First row, all columns
''' Output:
[[ 1  4  5 12 14]]
'''
print(A[:,2)] # All rows, second column
''' Output:
[ 5  9 11]
'''
print(A[:, 2:5)] # All rows, third to fifth columns
'''Output:
[[ 5 12 14]
 [ 9  0 17]
 [11 19 21]]
'''

As you can see, using NumPy (instead of nested lists) can make it easier to handle matrices, and we haven't even touched the basics yet. We recommend you study the NumPy package in detail, especially when you try to use Python for data science/During analysis.

NumPy Resources, you might find them helpful: