Numpy isscalar: How to Check If Element is Scalar

0
109
Numpy isscalar() Example | np isscalar() Function

Numpy isscalar() function is used to test if an element is scalar or not. The isscalar() returns Boolean value. The isscalar() function returns True if the input value is scalar and returns False otherwise.

Numpy isscalar()

To check if an element is scalar or not in Python, use the numpy isscalar() method. The isscalar() function returns True if the type of num is a scalar type.

The isscalar() method is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics.

Syntax

numpy.isscalar(input number)

Parameters

The isscalar() function takes only one parameter. The parameter is the input value for which we want to test if it is a scalar value or not.

Return Value

The isscalar() function returns a Boolean value, which is true if the input value is scalar and False otherwise.

Example programs on isscalar() method in Python

Write a Python program to show the working of the isscalar() function in Python.

# app.py

import numpy as np

a = 999
print("a =", a, "\n")
print("Scalar: ", np.isscalar(a))

b = [999]
print("b =", b, "\n")
print("Scalar: ", np.isscalar(b))

Output

a = 999 
 
Scalar:  True
b = [999] 
Scalar:  False

In this example, we’ve seen that bypassing 999 value to a variable “a” and checking it using isscalar() if it is scalar or not. In the second example, we passed it using a list which resulted in False.

Write a program to use the isscalar() function on a list containing more than 5 values and check on fraction values.

See the following code.

# app.py

import numpy as np
from fractions import Fraction

a = [10, 20, 30, 40, 50, 60]
print(a, "\n")
print("Scalar: ", np.isscalar(a), "\n")
print("Fraction Value: ", Fraction(10, 15), "\n")
print("Scalar: ", np.isscalar(Fraction(10, 15)))

Output

python3 app.py
[10, 20, 30, 40, 50, 60]

Scalar:  False

Fraction Value:  2/3

Scalar:  True

In this example, we have seen that bypassing the list of length six in the isscalar() function, we are getting false, and when we pass it in a fraction, which is 2/3 in the above example, we are getting true as it is only a scalar value.

Conclusion

Python numpy isscalar(num) is a logical function that returns true if the type of input num is scalar.

See also

Numpy iscomplex()

Numpy nan

Numpy isreal()

Numpy isfinite()

Numpy interpolant

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.