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'.


For more Practice: Solve these Related Problems:

  • Convert a nested list to a NumPy array and then back to a list, ensuring deep equality.
  • Transform a list of numbers into an array and revert it back, checking if both lists match.
  • Test round-trip conversion from a list to an array and back with mixed data types.
  • Convert a list to an array and then back to a list, verifying that the data types remain consistent.

Go to:


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.

Python-Numpy Code Editor:

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.