Home »
Python »
Python Programs
How to convert singleton array to a scalar value?
Given a singleton array, we have to convert it into a scaler value in Python.
Submitted by Pranit Sharma, on March 08, 2023
NumPy: Converting singleton array to a scalar value
Suppose that we are given a singleton array like 1x1x1x1x1x1… and we need to convert it into a scalar value as 1.
Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
To convert a singleton array into a scalar value, we can use the item() function over the array and it will return the corresponding scalar value.
Let us understand with the help of an example,
Python code to convert singleton array to a scalar value
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.array([[[[[[[[[1]]]]]]]]])
# Display original array
print("Original array:\n",arr,"\n")
print("Shape of arr is:\n",arr.shape,"\n")
# Getting the scalar value
res = arr.item()
# Display result
print("Result:\n",res,"\n")
Output:
Python NumPy Programs »