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.

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-39.php