# Null Space and Nullity of a matrix in Python

In this tutorial, we would learn about the null space and nullity of a matrix in Python.

Linear relationships among attributes can be found with the help of concepts of Null Space and Nullity.

## Null Space in Python

Null Space is the solution obtained from AB = 0 (where A is known matrix and B is a matrix which one needs to find).

First, import the sympy library which is used for symbolic mathematics. Then initialize a list A. Convert it into a matrix using Matrix() and do the same for the null space of A.

Check whether the given condition is satisfied or not by the null space.

```from sympy import Matrix

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A = Matrix(A)
NullSpace = A.nullspace()

NullSpace = Matrix(NullSpace)
print("Null Space : ", NullSpace)
print(A * NullSpace)```

Output-

```Null Space : Matrix([, [-2], ])
Matrix([, , ])```

The size of the null space of the matrix provides us with the number of linear relations among attributes.

## Nullity of a matrix in Python

Nullity of a matrix A is defined as the size of the null space of the matrix A and so are the linear relations.

First, import the sympy library which is used for symbolic mathematics. Then initialize a list A. Convert it into a matrix using Matrix(). Calculate the number of columns i.e. n and rank of the matrix and then the nullity for the same.

```from sympy import Matrix
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A = Matrix(A)
n = A.shape
rank = A.rank()
nullity = n - rank
print("Nullity : ", nullity)```

Output-

`Nullity :  1`

### Rank Nullity Theorem

Nullity of A + Rank(number of linearly independent rows or columns of the matrix) of A = Total number of attributes of A (total number of columns in A)

To see an example of rank, null space, and nullity of a matrix visit-

https://s-mat-pcs.oulu.fi/~mpa/matreng/eem3_2-2.htm