In this topic, we will learn how to convert a numpy matrix to list in python in a very easy and interesting way. Let’s see what we will use to convert a numPy matrix to list.
Convert a NumPy Matrix To List
Table Of Contents:
- Introduction
- Python code for converted List
- Output
- Conclusion
Introduction:
There are various methods to convert a numPy matrix to a list.
They are,
- Type Casting
- tolist() method
- list() constructor
- append() method
- list comprehesion
But now we use tolist() method to convert a numPy matrix to a list.
First we have to creating a multidimensional array (Numpy array) using the numpy.array() and printing the matrix before the conversion of list as “numpy matrix” and then convert numpy matrix to list using tolist() method.
Python code for converted List:
import numpy as np num_mat=np.array([[[2,3,4],[5,6,7],[9,0,1]]]) print("Numpy Matrix:",num_mat) lst=.num_mat.tolist() print("List converted from Numpy Matrix is ",lst)
import numpy as np:
Numpy is a python library used for working with arrays. It is used to working with ndarray and multidimensional arrays.
lst=num_mat.tolist():
The tolist() method is used to convert a multidimensional array (Numpy matrix) into a list.
Output:
Numpy Matrix: [[[2 3 4] [5 6 7] [9 0 1]]] List converted from Numpy Matrix is [[[2, 3, 4], [5, 6, 7], [9, 0, 1]]]
Here the output for the above program.
Conclusion:
In conclusion, The conversion of a NumPy matrix (multidimensional array) to a list in Python programming provides compact methods. By using tolist(), the numpy array is successfully converted into a list and maintaing the structure and elements of the source numpy matrix (multidimensional array) in python programming.