How to convert a matrix to a list in python ?


Examples of how to convert a matrix to a list in python:

Create a matrix with numpy

Let's consider the following matrix:

import numpy as np

A = np.array((1,2,3,4))

print(A)

gives

    array([1, 2, 3, 4])

Convert a matrix to a list with list()

To convert a matrix to a list in python, a solution is to use the built-in function called list():

l = list(A)

print(l)

returns

[1, 2, 3, 4]

Convert a matrix to a list with tolist()

Another solution is to use the numpy function tolist. Example with a 1d matrix:

l = m.tolist()

print(l)

gives

[1, 2, 3, 4]

Another example with a 2d matrix:

A = np.array(((1,2,3,4),(5,6,7,8)))

l = A.tolist()

returns

[[1, 2, 3, 4], [5, 6, 7, 8]]

References