w3resource

NumPy: Convert a given list into an array, then again convert it into a list


List to Array to List Comparison

Write a NumPy program to convert a given list into an array, then again convert it into a list. Check initial list and final list are equal or not.

This problem involves writing a NumPy program to convert a given array into a list and then back into a NumPy array. The task requires using NumPy's "tolist()" method to convert the array into a Python list and the "array()" function to convert the list back into a NumPy array.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a nested list 'a' containing lists as elements
a = [[1, 2], [3, 4]]

# Converting the nested list 'a' into a NumPy array 'x' using np.array()
x = np.array(a)

# Converting the NumPy array 'x' back to a Python nested list 'a2' using the tolist() method
a2 = x.tolist()

# Checking if the original list 'a' and the converted list 'a2' are equal
# This comparison checks if their elements and structure are the same
print(a == a2)

Output:

True                         

Explanation:

In the above code -

a = [[1, 2], [3, 4]] creates a nested list 'a' with two sublists containing integers.

The np.array(a) converts the nested list 'a' into a NumPy 2D array and stores in the variable 'x'.

a2 = x.tolist() statement converts the NumPy array 'x' back to a nested list named 'a2' using the 'tolist()' method.

Finally print(a == a2) checks if the original nested list 'a' and the reconstructed nested list 'a2' are equal. If they are equal, it prints 'True'; otherwise, it prints 'False'.

Python-Numpy Code Editor: