numpy.isscalar() in Python
Last Updated : 02 Jan, 2024
In this article, we will elucidate the `numpy.isscalar()` function through a well-documented code example and comprehensive explanation.
Python numpy.isscalar() Syntax
Syntax : numpy.isscalar(element)
Parameters:
element
: The input element to be checked for scalar properties.
Return Type:
bool
: Returns True
if the input element is a scalar, and False
otherwise.
What is numpy.isscalar() in Python?
The `numpy.isscalar()` is a function in the NumPy library of Python that is used to determine whether a given input is a scalar or not. A scalar is a single value, as opposed to an array or a more complex data structure. The function returns `True` if the input is a scalar and `False` otherwise. It is a useful tool for type checking in numerical and scientific computing applications where distinguishing between scalar and non-scalar values is often necessary.
Python numpy.isscalar() Function Example
Here are several commonly used examples of the `numpy.isscalar()` function, which we will elucidate for better understanding.
- Scalar Check in Python
- Check if a Variable is a Scalar
- Validating Input Type in a Function
- Using
isscalar()
in Conditional Logic
Scalar Check in Python
In this example Python program uses NumPy's `isscalar()` function to check if an input array `[1, 3, 5, 4]` is a scalar and prints the result. It further demonstrates the function's use by checking the scalar status of an integer (`7`) and a list (`[7]`), providing output indicating whether each input is a scalar.
Python3 # Python program explaining # isscalar() function import numpy as np # Input array in_array = [1, 3, 5, 4] print("Input array:", in_array) # Check if the input array is a scalar isscalar_values = np.isscalar(in_array) print("\nIs scalar:", isscalar_values) # Check if the input is a scalar (integer) print("\nisscalar(7):", np.isscalar(7)) # Check if the input (list) is a scalar print("\nisscalar([7]):", np.isscalar([7]))
Output :
Input array : [1, 3, 5, 4]
Is scalar : False
isscalar(7) : True
isscalar([7]) : False
Check if a Variable is a Scalar
In this example code uses NumPy's `isscalar()` to check if variables `x` (an integer) and `y` (a list) are scalars. It prints the results, indicating that `x` is a scalar (`True`) and `y` is not a scalar (`False`).
Python3 import numpy as np x = 42 y = [1, 2, 3] is_scalar_x = np.isscalar(x) is_scalar_y = np.isscalar(y) print(f"x is a scalar: {is_scalar_x}") print(f"y is a scalar: {is_scalar_y}")
Output:
x is a scalar: True
y is a scalar: False
Validating Input Type in a Function
In this example code defines a function `calculate_square` that takes a parameter `value`, checks if it is a scalar using `numpy.isscalar()`, and returns the square if it is. If the input is not a scalar, it raises a `ValueError`. It then calculates and prints the square of the scalar value 5, demonstrating the function's usage.
Python3 import numpy as np def calculate_square(value): if np.isscalar(value): return value**2 else: raise ValueError("Input must be a scalar") result = calculate_square(5) print("Square of 5:", result)
Output:
Square of 5: 25
Using isscalar()
in Conditional Logic
In this example code defines a function `process_data` that checks if the input is a scalar or a NumPy array, printing the corresponding message. It's demonstrated with an integer (prints the value), a NumPy array (prints "Processing NumPy array data"), and a string (prints "Unsupported data type").
Python3 import numpy as np def process_data(data): if np.isscalar(data): print("Processing scalar data:", data) elif isinstance(data, np.ndarray): print("Processing NumPy array data") else: print("Unsupported data type") process_data(10) process_data(np.array([1, 2, 3])) process_data("Invalid")
Output:
Processing scalar data: 10
Processing NumPy array data
Processing scalar data: Invalid
Similar Reads
numpy.isnan() in Python The numpy.isnan() function tests element-wise whether it is NaN or not and returns the result as a boolean array. Syntax :Â numpy.isnan(array [, out]) Parameters :Â array : [array_like]Input array or object whose elements, we need to test for infinity out : [ndarray, optional]Output array placed wit
2 min read
numpy.asscalar() in Python numpy.asscalar() function is used when we want to convert an array of size 1 to its scalar equivalent. Syntax : numpy.asscalar(arr) Parameters : arr : [ndarray] Input array of size 1. Return : Scalar representation of arr. The output data type is the same type returned by the inputâs item method. Co
1 min read
numpy.isinf() in Python numpy.isinf() test element-wise whether a value is positive or negative infinity. It returns a Boolean array with True where the input is either +inf or -inf and False otherwise. Example:Pythonimport numpy as np a = np.array([1, np.inf, -np.inf, 0, np.nan]) res = np.isinf(a) print(res)Output[False T
2 min read
numpy.issubclass_() function â Python numpy.issubclass_() function is used to determine whether a class is a subclass of a second class. Syntax : numpy.issubclass_(arg1, arg2) Parameters : arg1 : [class] Input class. True is returned if arg1 is a subclass of arg2. arg2 : [class or tuple of classes] Input class. If a tuple of classes, Tr
1 min read
numpy.isposinf() in Python The numpy.isposinf() function tests element-wise whether it is positive infinity or not and returns the result as a boolean array. Syntax : numpy.isposinf(array, y = None) Parameters:  array : [array_like]Input array or object whose elements, we need to test for infinity. y : [array_like]A boolea
2 min read