5 Best Ways to Convert a Python NumPy Array to a List of Lists

πŸ’‘ Problem Formulation: Converting NumPy arrays to regular lists of lists is a common task in data processing, especially when interfacing with APIs or libraries that do not support NumPy data structures. For instance, you might have a NumPy array like array([[1, 2], [3, 4]]) and want to convert it into a list of lists like [[1, 2], [3, 4]] for further processing or output formatting.

Method 1: The tolist() Method

NumPy itself provides a straightforward method to convert arrays into nested lists. The tolist() function is built into NumPy arrays and returns a list (or nested list for multidimensional arrays) that corresponds to the original array. It’s a simple and efficient way to accomplish this task for arrays of any shape and size.

Here’s an example:

import numpy as np

array = np.array([[1, 2], [3, 4]])
list_of_lists = array.tolist()

print(list_of_lists)

Output:

[[1, 2], [3, 4]]

This code creates a NumPy array with four elements organized into a 2×2 structure. By calling the tolist() method on this array, we convert it into a list of lists, with the structure being maintained. The printed output confirms the conversion.

Method 2: List Comprehension

List comprehension in Python provides a concise way to generate lists. It can easily be used to convert a NumPy array to a list of lists by iterating over the array and converting each sub-array into a list. This method is particularly useful for its readability and Pythonic style.

Here’s an example:

import numpy as np

array = np.array([[5, 6], [7, 8]])
list_of_lists = [list(row) for row in array]

print(list_of_lists)

Output:

[[5, 6], [7, 8]]

This snippet uses a list comprehension to iterate over each row of the NumPy array. The list() constructor is called on each row to convert it into a list, resulting in a list of lists that mirrors the shape of the original array.

Method 3: Using the map() Function

The map() function is a built-in Python function that applies a given function to each item of an iterable and returns a map object. When combined with the list() constructor, it can be used for converting each sub-array of a NumPy array into a list, resulting in a list of lists.

Here’s an example:

import numpy as np

array = np.array([[9, 10], [11, 12]])
list_of_lists = list(map(list, array))

print(list_of_lists)

Output:

[[9, 10], [11, 12]]

Here, we use map() to apply the list constructor to each row of the NumPy array. We then convert the map object to a list, which gives us our list of lists representation of the original array.

Method 4: Unpacking with a Loop

Another method to transform a NumPy array into a list of lists is by iterating through the array with a loop and unpacking each sub-array. This approach gives you full control over the conversion process and may be useful in more complex scenarios where additional operations are required during conversion.

Here’s an example:

import numpy as np

array = np.array([[13, 14], [15, 16]])
list_of_lists = []
for row in array:
    list_of_lists.append(list(row))

print(list_of_lists)

Output:

[[13, 14], [15, 16]]

In this code, we initialize an empty list and then loop through each row of the NumPy array, appending a list version of each row to our list_of_lists. It’s slightly more verbose than other methods but can be advantageous when dealing with complex data manipulations.

Bonus One-Liner Method 5: Using np.ndarray.tolist() Directly

For those who prefer concise, one-liner solutions, NumPy’s ndarray.tolist() method can also be used directly within a print statement or as part of another operation, eliminating the need for an intermediary variable.

Here’s an example:

import numpy as np

array = np.array([[17, 18], [19, 20]])
print(array.tolist())

Output:

[[17, 18], [19, 20]]

This snippet is a compact version of Method 1, where the tolist() method is applied directly within the print statement to convert the NumPy array to a list of lists and output the result.

Summary/Discussion

  • Method 1: tolist() Method. Straightforward and concise, provided by NumPy. Its main strength is efficiency, especially for large arrays. The downside is dependence on NumPy’s functionality (although it is not a significant issue for most use cases).
  • Method 2: List Comprehension. Clean and Pythonic, offering good readability. It can be less performant for very large arrays compared to Method 1.
  • Method 3: Using the map() Function. Functional programming approach, slightly less readable than list comprehension but equally powerful. The resulting map object must be explicitly converted to a list.
  • Method 4: Unpacking with a Loop. Most verbose, but offers maximum control and customizability. Useful when additional processing is needed within conversion.
  • Method 5: ndarray.tolist() Directly. Clean and compact one-liner for quick, in-place conversions. It’s essentially a shortcut for Method 1.