If your current version of data is in the format of a numpy array and you want an immutable version of that array data, you should convert your array into a tuple.
For a 1D array, you can use the tuple(numpy_array) Constructor, which should convert a numpy_array into a tuple. If your input numpy array contains np.int64 elements, it may not be directly converted to native Python integers in some cases.
For that, you must use the .tolist() function to ensure that the array elements are converted into standard Python integers before creating the tuple.
import numpy as np arr = np.array([11, 18, 19, 21]) print(arr) # Output: [11 18 19 21] print(type(arr)) # Output: <class 'numpy.ndarray'> # Converting to list for native Python integers python_list = arr.tolist() # Converting a list to tuple tup = tuple(python_list) print(tup) # Output: (11, 18, 19, 21) print(type(tup)) # Output: <class 'tuple'>
The final output is a tuple, which we verified using the type() function.
Working with a 2D array
When working with a multidimensional array like a 2D array, using tuple() directly won’t give the desired nested tuples. For that, you must convert each sub-array to a tuple recursively using comprehensions.
import numpy as np arr_2d = np.array([[11, 21], [31, 41]]) print(arr_2d) # Output: [[11 21] # [31 41]] print(type(arr_2d)) # Output: <class 'numpy.ndarray'> list_2d = arr_2d.tolist() # Converting to tuple tuple_2d = tuple(tuple(row) for row in list_2d) print(tuple_2d) # Output: ((11, 21), (31, 41)) print(type(tuple_2d)) # Output: <class 'tuple'>
The above code and output show that we first initialized a 2D array and used the .tolist() function to convert its np.int64 values into Python integers. Then, using tuple comprehension, we converted it into a tuple of tuples.
How about if our numpy array has string values? How do we deal with that?
Here is the solution:
import numpy as np # Initializing numpy array filled with strings main_array = np.array([['Krunal', 'Ankit'], ['Rushabh', 'Dhaval']]) print(main_array) # Output: [['Krunal' 'Ankit'] # ['Rushabh' 'Dhaval']] # Converting numpy arrays into tuples, ensuring native Python strings main_tuple = tuple(tuple(str(item) for item in row) for row in main_array) print(main_tuple) # Output: (('Krunal', 'Ankit'), ('Rushabh', 'Dhaval'))
Working with a 3D array
If you are dealing with a complex multi-dimensional array, you should create a custom recursive function that handles any type of conversion.
import numpy as np arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(arr_3d) # Output: [[[1 2] # [3 4]] # # [[5 6] # [7 8]]] print(type(arr_3d)) # Output: <class 'numpy.ndarray'> def array_to_tuple(arr): if isinstance(arr, np.ndarray): if arr.ndim == 0: return arr.item() # Handle 0D arrays # Recursive conversion return tuple(array_to_tuple(sub) for sub in arr) # Converting NumPy numbers to Python types elif isinstance(arr, (np.integer, np.floating)): return arr.item() return arr # Handles base case where elements are already Python types # Using the custom function directly on the NumPy array tuple_3d = array_to_tuple(arr_3d) print(tuple_3d) # Output: (((1, 2), (3, 4)), ((5, 6), (7, 8))) print(type(tuple_3d)) # Output: <class 'tuple'>
The above output shows that we successfully transformed a 3D array into a 3D tuple without losing any value.
Working with a 0D Array (Scalar)
If your input is scalar, it means a zero-dimensional array, and it must be explicitly converted to scalars.
import numpy as np arr_0d = np.array(5) print(arr_0d) # Output: 5 print(type(arr_0d)) # Output: <class 'numpy.ndarray'> scalar = arr_0d.item() if arr_0d.ndim == 0 else tuple(arr_0d) print(scalar) # Output: 5 print(type(scalar)) # Output: <class 'int'>
The final output is scalar (5), which means a class of integers and not a tuple.
Structured Arrays
If your input array has data of different structures, we can convert that structured array into a tuple by creating a customized function.
import numpy as np # Defining a structured NumPy dtype dt = np.dtype([('name', 'S10'), ('age', 'i4')]) # Creating a structured NumPy array arr_struct = np.array([('Krunal', 32), ('Yogita', 28)], dtype=dt) print(arr_struct) # Output: [(b'Krunal', 32) (b'Yogita', 28)] print(type(arr_struct)) # Output: <class 'numpy.ndarray'> def array_to_tuple(arr): if isinstance(arr, np.ndarray): if arr.dtype.names: # Structured array case return tuple(tuple(array_to_tuple(arr[field]) for field in arr.dtype.names) for arr in arr) if arr.ndim == 0: return arr.item() # Converting 0D arrays to Python scalars # Recursively process the array return tuple(array_to_tuple(sub) for sub in arr) elif isinstance(arr, (np.integer, np.floating)): return arr.item() # Convert NumPy numbers to Python types elif isinstance(arr, bytes): # Converting byte strings to normal Python strings return arr.decode('utf-8').strip() return arr # Returning already-native Python types as-is # Converting the structured array to a tuple tuple_struct = array_to_tuple(arr_struct) print(tuple_struct) # Output: (('Krunal', 32), ('Yogita', 28)) print(type(tuple_struct)) # Output: <class 'tuple'>
If you want to convert a tuple to a numpy array, use the numpy.array() method.
That’s all!