Open In App
Related Articles

Python | Convert Numpy Arrays to Tuples

Improve Article
Improve
Save Article
Save
Like Article
Like

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.

Python3




# 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 

Python3




# 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'))

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials