Python - How to Convert a NumPy Matrix to List?

Learn, how to convert a NumPy matrix to list in Python? By Pranit Sharma Last updated : December 28, 2023

A Python list is a collection of heterogeneous elements and it is mutable in nature. Elements inside the list are encapsulated in square brackets. A list is considered a series or collection and we can perform operations like insert, update, and delete with its elements.

Problem statement

Suppose that we are given a numpy matrix and we need to convert it into a flat Python list.

Making a List from NumPy Matrix

To convert a NumPy matrix to list, we can simply use .tolist() function on the numpy matrix which will directly convert the matrix into a flat 1D list.

Let us understand with the help of an example,

Python code to convert a NumPy matrix to list

# Import numpy
import numpy as np

# Creating a numpy matrix
mat = np.matrix([1, 2, 3])

# Display original matrix
print("Original matrix:\n",mat,"\n")

# Converting matrix into a list
res = mat.tolist()

# Display result
print("Result:\n",res)

Output

Example: Making a List from NumPy Matrix

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.