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

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.

Problem statement

Suppose that we are given a singleton array like 1x1x1x1x1x1… and we need to convert it into a scalar value as 1.

NumPy: Converting singleton array to a scalar value

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 program 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

The output of the above program is:

Example: How to convert singleton array to a scalar value?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.