Python Tutorials

# Python Lists and Matrix with Numpy

Matrices (plural form of a matrix) is a 2-dimensional array of data in rows and columns. Matrices are a major part of linear algebra and they can be wrangled to do extraordinary things in mathematics. In this tutorial, you will learn how to create matrices from lists in Python. Also, we will utilize the NumPy library to create NumPy arrays; called matrices.

Specifically, by the end of this tutorial, you will learn:

• What matrices are
• How to represent matrices in Python
• How to access a specific element in a matrix
• Addition and subtraction of matrices
• Using Numpy for matrix creation and manipulation
• Numerical Computation with Numpy arrays
• Transposing a matrix with NumPy
• Slicing a Matrix with NumPy

## What is a Matrix

A matrix is simply a way of collecting data in rows and columns. We know data can be collected in sets, lists, etc. When it comes to matrices, they are split into rows and columns. If you are not sure what the row and column are, the row is the horizontal axis. The column on the other hand is the data seen in the vertical axis.

A matrix in mathematics can be defined by its size; the size of the matrix being the number of rows by columns.  Below is an example of a matrix.

Since it has 3 rows and 2 columns, it is thus a 3 by 2 matrix.

On row 1, you have values 2, -1
On row 2, you have values 0, 5
On row 3, you have values 4, 9
In column 1, you have values 2, 0, 4
In column 2, you have values -1, 5, 9

Let’s see how to represent this in Python.

## Representing a Matrix in Python.

There is no straight way of representing a matrix data type in Python. The closest datatype to a matrix is the list data type, and thus, is typically used to create matrices.

However, the Numpy library provides another way of representing matrices in Python, the NumPy array data type. We will discuss both methods in this tutorial.

## Creating a Matrix using Python Lists.

A list in python is a collection of homogenous data, encapsulated by square brackets and each separated by a comma. By default, a list is seen as a matrix with one row while the column depends on the number of elements it has. Let’s see an example.

```#create a one-dimensional list
list_1 = [1, -2, 0]```

The list created is a 1 by 3 matrix because it contains 3 elements and it’s a single list. The big question is then, how do we create lists with more than 1 row? Nested lists!

If we wish to create a list with more than one row, we open 2 square brackets and encapsulate each row inside a square bracket. See how it’s done below.

```#create a list with more than one row
list_1 = [['first row'],
['second row'],
['third row'],
...
['last row']]```

Let’s now create a 3 by 2 matrix using nested lists.

```#create a 3 by 2 list
list_1 = [[2, -1],
[0, 5],
[4, 9]]```

## Accessing Element in a Python List

If you wish to access specific elements in a list, you can do so using indexing. To get the entire row, you pass the row index in square brackets. Let’s say we want to access the first row in the list above. We can write

```#create a 3 by 2 list
list_1 = [[2, -1],
[0, 5],
[4, 9]]

#print the first row
print(list_1)```

`Output:[2, -1]`

To get a specific element, pass the row and column index in separate square brackets, as in [‘row index’][‘column index’]. In the above matrix, if we wish to access the element in the first row and second column, we can do it with the following code.

```#create a 3 by 2 list
list_1 = [[2, -1],
[0, 5],
[4, 9]]

#print the element in the first row and second column
print(list_1)```

`Output:-1`

You can add lists as matrices in Python. See the example below.

```#define the two  matrices to be added
list_1 = [[1, 4, 3],
[10,2,4],
[-1,3,2]]

list_2 = [[3, 6, -6],
[2,5,-2],
[-2,6,3]]

#define a list to store the result
[0,0,0],
[0,0,0]]

#add the two lists based on their index
for i, _ in enumerate(list_1):
for j, _ in enumerate(list_2):

#To Print the matrix

Output:

` The addition of list_1 and list_2 is [[4, 10, -3], [12, 7, 2], [-3, 9, 5]]`

## Subtracting of Matrices in Python.

Just as in addition, you can do an element-based subtraction with nested lists. See an example below.

```#define the two  matrices to be added
list_1 = [[1, 4, 3],
[10,2,4],
[-1,3,2]]

list_2 = [[3, 6, -6],
[2,5,-2],
[-2,6,3]]

#define a list to store the result
[0,0,0],
[0,0,0]]

#multiply the two lists based on their index
for i, _ in enumerate(list_1):
for j, _ in enumerate(list_2):

#To Print the matrix
print(f" The subtraction of list_1 and list_2 is \n{addtion_result}")```

Output:

The subtraction of list_1 and list_2 is
[[-2, -2, 9], [8, -3, 6], [1, -3, -1]]

## Using NumPy Library for Matrix Creation and Manipulation

Numpy is a popular library that is used for numerical computations in python. As a matter of fact, the name NumPy stands for Numerical Python. You can create matrices using the NumPy library. In this section, we shall create and do computations in matrices using Numpy. If you don’t have the library installed on your machine, you can do so by typing

pip install numpy

on your command prompt. It is vital to state that NumPy comes pre-installed if you are using a Jupyter notebook. You would not need to install NumPy again.

Once you have numpy successfully installed, let’s now begin to create matrices with the library.

## Creating a Matrix with Numpy

In Numpy, matrices are in the form of a NumPy array. Lists are converted to Numpy arrays by calling the array() method and passing the list. Let’s see an example.

```#import the necessary library
import numpy as np
#define a one-dimensional array
matrix_a = np.array([1, 2, 3])

#print the matrix and its type
print(matrix_a)
print(type(matrix_a))```

Output:

[1 2 3]<class ‘numpy.ndarray’>

As seen from the result, the matrix of an object with an ndarray (n-dimensional  array) datatype

## Addition of Matrices in Numpy

The addition of matrices in NumPy is way easier than list addition in the earlier example. After defining the arrays to be added, you simply use the + operator to indicate you want the matrices to be added. See the example below.

```#import the necessary library
import numpy as np

#define the matrices to be added
matrix_1 = np.array([[1, 4, 3],
[10,2,4],
[-1,3,2]])

matrix_2 = np.array([[3, 6, -6],
[2,5,-2],
[-2,6,3]])

#To Print the matrix

Output:

`The addition of list_1 and list_2 is [[1, 4, 3], [10, 2, 4], [-1, 3, 2], [3, 6, -6], [2, 5, -2], [-2, 6, 3]]`

Easy right?

.

The same thing goes for matrix subtraction

## Matrix Subtraction with Numpy

```#import the necessary library
import numpy as np

#define the matrices to be added
matrix_1 = np.array([[1, 4, 3],
[10,2,4],
[-1,3,2]])

matrix_2 = np.array([[3, 6, -6],
[2,5,-2],
[-2,6,3]])

sub_result = matrix_1 - matrix_2

#To Print the matrix
print(f" The subtraction of list_2 from list_1 is \n{sub_result}")```

`Output:The subtraction of list_2 from list_1 is[[-2 -2 9][ 8 -3 6][ 1 -3 -1]]You can also do the matrix multiplication of two matrices.`

## Multiplying Two Matrices in Numpy

To multiply two matrices in Numpy, you can use the dot() method of NumPy. See an example

```#import the necessary library
import numpy as np

#define the matrices to be added
matrix_1 = np.array([[1, 4, 3],
[10,2,4],
[-1,3,2]])

matrix_2 = np.array([[3, 6, -6],
[2,5,-2],
[-2,6,3]])

#multiply the two matrices
result = np.dot(matrix_1, matrix_2)

#To Print the matrix
print(f" The multiplication of list_1 and list_2 is \n{result}")```

`Output:The multiplication of list_1 and list_2 is[[ 5 44 -5][ 26 94 -52][ -1 21 6]]`

## Matrix Transpose in NumPy

Transposing a matrix involves switching the rows to become columns and switching columns to rows as well. To return the transpose of a matrix, the transpose() method can be called

```#import the necessary library
import numpy as np

#define the matrix
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8,],
[9, 10, 11, 12]])

print(matrix.transpose())
```

`Output:[[ 1 5 9][ 2 6 10][ 3 7 11][ 4 8 12]]`

Alternatively, you can use the T attribute.

```#import the necessary library
import numpy as np

#define the matrix
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8,],
[9, 10, 11, 12]])

print(matrix.T)```

`Output:[[ 1 5 9][ 2 6 10][ 3 7 11][ 4 8 12]]`

As seen, it produces the same result.

## How to Slice Matrices

Like in lists, slicing is the process of returning a portion of a matrix. Here are some key things to note about slicing.

• When sorting, the start and end index is indicated with the syntax[start: end]
• When the start index is not passed, Python takes the start index from the beginning of the list.
• When the end index is not passed, Python takes the end index as the end of the list.
• When counting from the beginning, the indexing begins from 0, 1, 2, 3… When counting from the end, the indexing begins from -1, -2, -3, etc.
• When the end index is defined, the sliced array returns index minus 1. If say the end index was 3, the slicing stops as the 2nd index

Now let’s apply some of these with concrete examples.

## Slicing a One-Dimensional Matrix.

```#import the necessary library
import numpy as np

#define the matrix
matrix = np.array([1, 2, 3, 4, 5, 6, 7])

#slice the first row
print('First row is')
print(matrix[:2])

#slice the second column
print('Second column is')
print(matrix[1:6])

#slice the first row from behind
print('First row from to the ')
print(matrix[:-1])```

`Output:First row is[1 2]Second column is[2 3 4 5 6]First row from behind is[1 2 3 4 5 6]`

## Slicing a Multidimensional Array

When slicing a multidimensional array, the row, and column are separated by a comma.

```#import the necessary library
import numpy as np

#define the matrix
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8,],
[9, 10, 11, 12]])

#slice the last row
print('Last row is')
print(matrix[2, :])

#slice the second column
print('Second column is')
print(matrix[:, -3])

#slie from the second column
print('Matrix to the second column ')
print(matrix[:, :2])```

`Output:Last row is[ 9 10 11 12]Second column is[ 2 6 10]Matrix to the second column[[ 1 2][ 5 6][ 9 10]]`

`Let’s unpack the code.This was the initial matrix that was sliced[[ 1 2 3 4][ 5 6 7 8][ 9 10 11 12]]`

• In the first print statement, we sliced [2, :]. The row index was set to 2, while the column was set as the range of all the elements. This is why the elements in the third row were printed. Recall that python indexes from 0. Since index 2 would be the 3rd row.

[ 9 10 11 12]

• In the next print statement, we sliced [:, -3]. The row index was a range of all numbers, while the column index was set to -3. Recall that when a negative index is passed, Python counts from the end starting from -2. This is why -3 returns the 3rd column from behind or the 2nd index from the beginning.
[ 2  6 10]
• In the next print statement, we sliced [:, :2]. The row index was set to print all the rows in the matrix. The second column was set to return a range from the beginning to the second index. This is why the slicing returns the first two columns.

`[[ 1  2]`
`[ 5  6][ 9 10]]`

## Let’s conclude.

In this tutorial, you have discovered how to create matrices using lists and NumPy arrays in Python. You also learned how to do numerical computations on the matrices in Numpy. Worthy of mention is the dot() and transpose() method.

Finally, you learned how to slice a specific chunk of matrices by specifying its index or range.

If you have any questions, feel free to leave them in the comment section and I’d do my best to answer them.

### One Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.