Convert NumPy array to list in Python
In this tutorial, we will be learning how to convert a NumPy array into a list in Python. It is very simple, you just need to use a basic syntax as:
mylist = myarr.tolist()
Steps you need to follow for the task:
- Import NumPy module.
- Create an array, display it with its type.
- Follow the above syntax to convert it into a list.
- Display the list created above with its type.
Converting 1-D array into a Python list
For this, firstly import the NumPy module, and then create a 1-D, convert it into a list and display the type. If it shows list, we have successfully converted an array into a list. So, moving towards the coding part below-
import numpy as np print("Array:") myarr = np.array([1, 2,3, 4, 5]) print(myarr) print(type(myarr)) mylist = myarr.tolist() print("List:") print(mylist) print(type(mylist))
After running the above code we will see the output given below:
Array: [1 2 3 4 5] <class 'numpy.ndarray'> List: [1, 2, 3, 4, 5] <class 'list'>
As you can see in the above code, we have created an array that was later converted into a list using the above method.
Converting Multidimensional array into a list
As we have converted a 1-D array into a list, in the same way we can do this for a multi-dimensional array too.
Let’s move to the snippet:
import numpy as np print("Array:") myarr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(myarr) print(type(myarr)) mylist = arr.tolist() print("List:") print(mylist) print(type(mylist))
Below is the output is given for the above Python code:
Array: [[1 2 3] [4 5 6] [7 8 9]] <class 'numpy.ndarray'>
List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] <class 'list'>
As you can see in the output for our code, a multi-dimensional NumPy array was created and then we convert it into a list with a few lines of Python code.
Here we have just completed the tutorial on “How to convert an array into a list” with few lines of easy-to-understand code.
Hope you enjoyed reading and implementing it. Feel free to comment and share your reviews. Thanks for reading!