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 :
- Import the NumPy library with the alias np.
- Initialize a 2D NumPy array named ini_array with two rows and two columns.
- 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().
- Assign the resulting tuple of tuples to a variable called result.
- Print the result array as a string using the print() function.
Python3
import numpy as np
ini_array = np.array([[ 'manjeet' , 'akshat' ], [ 'nikhil' , 'akash' ]])
result = tuple ( map ( tuple , ini_array))
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
import numpy as np
ini_array = np.array([[ 'manjeet' , 'akshat' ], [ 'nikhil' , 'akash' ]])
result = tuple ([ tuple (row) for row in ini_array])
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