Using ndarray.tolist() method in NumPy (5 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

Introduction

The ndarray.tolist() method offered by NumPy is a useful tool for converting NumPy arrays back to standard Python lists. This conversion is essential in scenarios where you require the functionality or APIs specific to Python lists, or when you need to output data in a format that can be easily JSON serialized. This tutorial will guide you through the usage of ndarray.tolist() with a progression from basic to advanced examples, illustrating the versatility of this method in different contexts.

What does ndarray.tolist() do?

Before diving into examples, let’s briefly understand what the ndarray.tolist() method does. Simply put, it converts a NumPy array, regardless of its dimensionality, into a nested list where the nesting level corresponds to the dimensionality of the array. This method does not require any arguments and the conversion is intuitive and straightforward.

Example 1: Converting a 1-D Array to a List

import numpy as np

# Creating a 1-D NumPy array
array1D = np.arange(5)
print(f"Original array: {array1D}")

# Convert the array to a list
list1D = array1D.tolist()
print(f"Converted list: {list1D}")

Output:

Original array: [0 1 2 3 4]

Converted list: [0, 1, 2, 3, 4]

In this basic example, we converted a simple one-dimensional array to a list. The conversion retains the data ordering and type.

Example 2: Converting a 2-D Array to a Nested List

import numpy as np

# Creating a 2-D NumPy array
array2D = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Original array: {array2D}")

# Convert the array to a nested list
list2D = array2D.tolist()
print(f"Converted nested list: {list2D}")

Output:

Original array: [[1, 2, 3], [4, 5, 6]]

Converted nested list: [[1, 2, 3], [4, 5, 6]]

This example demonstrates the conversion of a two-dimensional array into a nested list, preserving the structure of the data.

Example 3: Working with 3-D Arrays

import numpy as np

# Creating a 3-D NumPy array
array3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(f"Original array: {array3D}")

# Convert the array to a nested list of lists
list3D = array3D.tolist()
print(f"Converted nested lists of lists: {list3D}")

Output:

Original array: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

Converted nested lists of lists: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

Here, a more complex three-dimensional array is converted into a deeply nested list, again emphasizing the method’s ability to handle multi-dimensional data.

Example 4: Conditional Array to List Conversion

import numpy as np

# Creating an array with a condition
arrayCond = np.arange(10)
filteredArray = arrayCond[arrayCond > 5]
print(f"Filtered array: {filteredArray}")

# Convert the filtered array to a list
filteredList = filteredArray.tolist()
print(f"Converted list: {filteredList}")

Output:

Filtered array: [6 7 8 9]

Converted list: [6, 7, 8, 9]

This example showcases the application of ndarray.tolist() on an array that has been filtered based on a condition, elucidating its usefulness in data processing workflows.

Example 5: Integrating with JSON

import numpy as np
import json

# Creating a mixed type 2-D array
arrayMixed = np.array([[1, 'two', 3.0], [4, 'five', 6.7]])
listMixed = arrayMixed.tolist()

# Convert list to a JSON string
jsonString = json.dumps(listMixed)
print(f"JSON string: {jsonString}")

Output:

JSON string: [["1", "two", "3.0"], ["4", "five", "6.7"]]

This advanced example illustrates how you can combine ndarray.tolist() with Python’s json module to convert a NumPy array with mixed data types to a JSON string, demonstrating its significance in serialization processes.

Conclusion

The ndarray.tolist() method is highly effective for converting NumPy arrays to Python lists, facilitating easy manipulation and compatibility with Python-only libraries and features. The presented examples range from simple conversions to more complex applications, highlighting the method’s utility across various context. Whether integrating with JSON for web development or processing filtered data, ndarray.tolist() proves to be an indispensable tool in the data scientist’s toolkit.