Working with various types of data is an extremely common activity in Python. Often, you may need to distinguish between an array and a scalar and this is the primary requirement to efficiently handle numerical computations. There are libraries like NumPy, which give you various functions to check whether a variable is an array or a scalar.
In this blog, we are going to explore various methods using functions such as isinstance(), ndim, len(), and isscalar() by which you can determine if the variable is an array or a scalar in Python.
Table of Contents:
Ways to Identify Arrays and Scalars in Python
1. Using isinstance() for Type Checking:
The isinstance() function checks whether the variable you’re using is an instance of numpy.ndarray (array) or a standard scalar type. It is one of the easiest ways to check the variable type; it also works well with inheritance, making it better suited for more general data type checks.
import numpy as np
def check_yourData(variable):
if isinstance(variable, np.ndarray):
return "Array"
elif isinstance(variable, (int, float, complex, str)):
return "Scalar"
else:
return "Try Again"
print(check_yourData(np.array([1, 2, 3])))
print(check_yourData(42))
Output:
Array
Scalar
2. Using NumPy’s ndim Attribute
When you are working with NumPy, ndim is an attribute that returns the dimensions of an array. Scalars have zero dimensions (ndim == 0)
import numpy as np
arr = np.array([89, 20, 30])
scalar = np.array(50)
print(arr.ndim)
print(scalar.ndim)
Output:
1 (Array)
0 (Scalar)
3. Using Numpy’s isscalar() Function
NumPy gives the np.isscalar() function for checking if a variable is a scalar.
import numpy as np
print(np.isscalar(10))
print(np.isscalar(np.array([1, 2, 3])))
Output:
True
False
4. Checking len() for Non-NumPy Data
For the generic Python data structures like the lists and tuples, checking with the len() can help to distinguish between the array and scalars. Scalars will give an error when it is passed into len().
def is_scalar(variable):
try:
len(variable)
return False
except TypeError:
return True
print(is_scalar(10))
print(is_scalar([1, 2, 3]))
Output:
True
False
Examples of Identifying the Scalars and Arrays in NumPy
This example explains how to identify scalars and arrays in a NumPy-based dataset using np.isscalar() and isinstance() functions.
import numpy as np
data = [50, np.array(10), np.array([10, 20, 30])]
for variable in data:
if np.isscalar(variable):
print(f"{variable} is a Scalar")
elif isinstance(item, np.ndarray):
print(f"{variable} is an Array")
Output:
50 is a Scalar
10 is an Array
[10 20 30] is an Array
Handle the Mixed Data Types
When you are working with mixed data types, you can use isinstance() along with the np.isscalar():
import numpy as np
def check_data(variable):
if np.isscalar(variable):
return "Scalar"
elif isinstance(variable, (list, tuple, np.ndarray)):
return "Array"
else:
return "Try Again"
print(check_data(3.14)) # Output: Scalar
print(check_data(np.array([10, 20, 30]))) # Output: Array
print(check_data("Hello Intellipaat")) # Output: Scalar
Output:
Scalar
Array
Scalar
Conclusion
Identifying if a variable is an array or a scalar is very crucial for writing powerful Python code. You can use built-in functions such as type(), isinstance(), and len(), and you can efficiently determine the type of a variable. These are the methods that help to stop when you are handling mixed data types in any Python code.