w3resource

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

NumPy: Basic Exercise-39 with Solution

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.

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)

Sample 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:

Previous: NumPy program to convert a given array into bytes, and load it as array.
Next: NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.