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


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

Python NumPy Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.