Open In App

Python | Convert Numpy Arrays to Tuples

Given a numpy array, write a program to convert numpy array into tuples.

Examples – 



Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]])
Output:  ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1))

Input:  ([['manjeet', 'akshat'], ['nikhil', 'akash']])
Output:  (('manjeet', 'akshat'), ('nikhil', 'akash'))

Method #1: Using tuple and map 

Step-by-step approach :



  1. Import the NumPy library with the alias np.
  2. Initialize a 2D NumPy array named ini_array with two rows and two columns.
  3. Convert the NumPy array into a tuple of tuples using the map() function and tuple() constructor. This is done by applying the tuple() function to each row of the NumPy array using map().
  4. Assign the resulting tuple of tuples to a variable called result.
  5. Print the result array as a string using the print() function.




# Python code to demonstrate
# deletion of columns from numpy array
 
import numpy as np
 
# initialising numpy array
ini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']])
                         
 
# convert numpy arrays into tuples
result = tuple(map(tuple, ini_array))
 
# print result
print ("Resultant Array :"+str(result))

Output: 
 

Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))

Time Complexity: O(n), where n is the number of elements in the numpy array.
Auxiliary Space: O(n), where n is the number of elements in the numpy array. 

Method #2: Using Naive Approach 




# Python code to demonstrate
# deletion of columns from numpy array
 
import numpy as np
 
# initialising numpy array
ini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']])
                         
 
# convert numpy arrays into tuples
result = tuple([tuple(row) for row in ini_array])
 
# print result
print ("Result:"+str(result))

Output: 

Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))

Article Tags :