How To Convert a NumPy Array to List in Python
Introduction
With NumPy, np.array
objects can be effortlessly converted to a Python list using the tolist()
function, a highly efficient and straightforward method. The tolist()
function doesn’t accept any arguments, simplifying its usage. If the array is one-dimensional, it produces a clean and simple list containing the array’s elements. For a multi-dimensional array, the function generates a structured and easily navigable nested list, preserving the hierarchical arrangement of the data. This functionality is particularly useful when working with diverse data structures, ensuring seamless integration with Python’s native list operations.
Prerequisites to Convert a NumPy Array
In order to complete this tutorial, you will need:
- Familiarity with installing Python 3 and using pip to install packages.
- Familiarity with coding in Python. Refer to the How to Code in Python 3 series or use VS Code for Python.
- This tutorial was tested with Python 3.9.6 and NumPy 1.23.3.
Converting one-dimensional NumPy Array to List
Let’s construct a one-dimensional array of [1, 2, 3]
:
import numpy as np
# 1d array to list
arr_1 = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr_1}')
This code will output:
NumPy Array:
[1 2 3]
Now, let’s use tolist()
:
import numpy as np
# 1d array to list
arr_1 = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr_1}')
list_1 = arr_1.tolist()
print(f'List: {list_1}')
This new code to Convert a NumPy Array will output:
List: [1, 2, 3]
The array has been converted from numpy scalars to Python scalars.
Converting multi-dimensional NumPy Array to List
Let’s construct a multi-dimensional array of [[1, 2, 3], [4, 5, 6]]
:
import numpy as np
# 2d array to list
arr_2 = np.array([[1, 2, 3], [4, 5, 6]])
print(f'NumPy Array:\n{arr_2}')
This code will output:
NumPy Array:
[[1 2 3]
[4 5 6]]
Now, let’s use tolist()
:
import numpy as np
# 2d array to list
arr_2 = np.array([[1, 2, 3], [4, 5, 6]])
print(f'NumPy Array:\n{arr_2}')
list_2 = arr_2.tolist()
print(f'List: {list_2}')
This new code to Convert a NumPy Array will output:
List: [[1, 2, 3], [4, 5, 6]]
The array has been converted from numpy scalars to Python scalars.
Conclusion
In this article, you learned how to Convert a NumPy Array and effectively use the tolist()
method to convert np.array
objects into Python lists, making it easier to manipulate and integrate data within Python’s native environment. This versatile function is applicable to both one-dimensional and multi-dimensional arrays, ensuring flexibility across various use cases. Whether you’re working with simple datasets or complex hierarchical structures, tolist()
provides a seamless way to bridge the gap between NumPy and Python’s built-in data types, enhancing your data processing capabilities.