Convert 2D NumPy array to list of lists in python

How to convert 2D NumPy array to list of lists in python ?

In this article we will discuss about different ways of converting NumPy array to list of lists in Python. So let’s start exploring the topic.

Converting a 2D Numpy Array to list of lists using tolist() :

In NumPy module of Python, there is a member function tolist() which returns a list congaing the elements of the array. If the array is a 2D array then it returns lists of list.

So, let’s see the implementation of it.

#Program :

import numpy as np
# 2D Numpy array created
arr = np.array([[11, 22, 33, 44],
                [55, 66, 77, 88],
                [12, 13, 23, 43]])

#printing the 2D array                
print(arr)
# Converting 2D Numpy Array to list of lists
list_of_lists = arr.tolist()
#Printing the list of lists
print("The list is")
print(list_of_lists)
Output :
[[11, 22, 33, 44], 
[55, 66, 77, 88], 
[12, 13, 23, 43]]
The list is
[[11, 22, 33, 44], [55, 66, 77, 88], [12, 13, 23, 43]]

Converting a 2D Numpy array to list of lists using iteration :

We can iterate a 2D array row by row and during iteration we can add it to the list. And at the end we can get the list of lists containing all the elements from 2D numpy array.

#Program :

import numpy as np
# 2D Numpy array created
arr = np.array([[11, 22, 33, 44],
                [55, 66, 77, 88],
                [12, 13, 23, 43]])

#printing the 2D array                
print(arr)
# Converting a 2D Numpy Array to list of lists
#iterating row by row using for loop
list_of_lists = list()
for row in arr:
    list_of_lists.append(row.tolist())
#Printing the list of lists
print("The list is")
print(list_of_lists)
Output :
[[11, 22, 33, 44], 
[55, 66, 77, 88], 
[12, 13, 23, 43]]
The list is
[[11, 22, 33, 44], [55, 66, 77, 88], [12, 13, 23, 43]]

Converting a 2D Numpy Array to a flat list :

In both the example, we observed that a 2D NumPy array converted into list of lists. But we can also convert it into a  flat list (not a list of lists) . So, for that first we can convert the 2D NumPy array into 1D Numpy array by using flatten() method.. Then call the tolist() function to convert it into flat list.

#Program :

import numpy as np
# 2D Numpy array created
arr = np.array([[11, 22, 33, 44],
                [55, 66, 77, 88],
                [12, 13, 23, 43]])

#printing the 2D array                
print(arr)

# Converting 2D Numpy array to a flat list
my_list = arr.flatten().tolist()
#Printing the list of lists
print("The list is")
print(my_list)
Output :
[[11, 22, 33, 44], 
[55, 66, 77, 88], 
[12, 13, 23, 43]] 
The list is [11, 22, 33, 44, 55, 66, 77, 88, 12, 13, 23, 43]