Convert 2D NumPy array to list of lists in python

In this article, we will learn how to convert 2D Numpy Array to a nested list i.e. list of lists.

Convert 2D Numpy Array to list of lists using tolist()

In Python’s numpy module, the ndarray class provides a member function tolist(), which returns a list containing the copy of elements in the numpy array. If numpy array is 2D, then it returns a list of lists. For example,

import numpy as np

# Create 2D Numpy Array
arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [3, 3, 3, 3]])

print(arr)

# Convert 2D Numpy Array to list of lists
list_of_lists = arr.tolist()

print(list_of_lists)  

Output:

[[1 2 3 4]
 [5 6 7 8]
 [3 3 3 3]]
[[1, 2, 3, 4], [5, 6, 7, 8], [3, 3, 3, 3]]

It returned a list of lists with the copy of elements in the two dimensional numpy array.

Convert 2D Numpy array to list of lists using iteration

Create an empty list and iterate over all the rows in 2D numpy array one by one. For each of the row, we can add it to the list as a sub list. At the end of the iteration, we will have a list of lists containing all the elements from 2D numpy array. For example,

import numpy as np

# Create 2D Numpy array filled with 0's
arr = np.zeros( (4, 5), dtype=np.int64)

print(arr)

# Convert 2D Numpy Array to list of lists
list_of_lists = list()
for row in arr:
    list_of_lists.append(row.tolist())

print(list_of_lists)

Output:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Convert 2D Numpy Array to a flat list

In both the previous solutions, we converted the 2D Numpy array to a nested list i.e. list of lists. What if we want to convert 2D array to a flat list ? For that we need to first flatten the 2D numpy array to a 1D numpy array and then call tolist() function on that. For example,

import numpy as np

# Create 2D Numpy array filled with 0's
arr = np.zeros( (4, 5), dtype=np.int64)

print(arr)

# Convert 2D Numpy array to a flat list
num_list = arr.flatten().tolist()

print(num_list)

Output:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Summary:

In this article we learned about different ways to convert a 2D Numpy array to either list of lists or a flat list in python

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top