How to check if the NumPy array is Empty in Python
In this tutorial, we are going to learn about how to check if the NumPy is empty or not in Python with the help of examples.
Checking if a NumPy array is empty using arr.size property
To check if the NumPy array is empty in Python, we can use the arr.size property where it returns number of elements in a NumPy array, if the size is 0
we can considered it as a empty array..
Note: Empty arrays are treated as falsy values in Python.
Here is an example:
import numpy as np
homes = np.array([])
if homes.size == 0:
print("NumPy array is Empty")
else:
print("NumPy array is not Empty")
Output:
"NumPy array is Empty"
Converting NumPy array to list
We can check if a numpy array is empty or not by converting it to a list and pass it to the len() function.
The len()
function takes the list as an argument and returns the number of elements in it.
Here is an example:
import numpy as np
homes = np.array([])
if len(homes.toList()) == 0:
print("NumPy array is Empty")
else:
print("NumPy array is not Empty")
Output:
NumPy array is Empty
In the example above, we first converted the NumPy array to a list by using the toList()
method and passed to the len() function. So it returns the number of elements from an array. If number of elements is 0 it will print NumPy array is Empty
otherwise NumPy array is not Empty
.
Additional resources
You can also check following tutorials in Python: