Python does not have an array as a built-in data type, but you can use a library like numpy to create an array and perform various operations on the array.
Check if array is empty Python
To check if an array is empty in Python, use the numpy.ndarray.size property and compare it with zero(0). If the number is 0, then an array is empty. To work with an array in Python, import numpy library. To create an array, use the np.array() method.
import numpy as np empty_array = np.array() if_array_empty = empty_array.size == 0 print(if_array_empty)
To create an empty array in Python, use the np.array().
In this example, we are comparing an empty array with 0, and since it is the same, we get True.
If the array was not empty, then it would have returned False.
import numpy as np empty_array = np.array([21, 19]) if_array_empty = empty_array.size == 0 print(if_array_empty)
It returns False because the array is not empty.
Checking an empty array using np.any() function
The np.any() function checks whether any array item along a given axis evaluates to True.
import numpy as np emp_arr = np.array() flag = not np.any(emp_arr) if flag: print('Your array is empty') else: print('Your array is not empty')
Your array is empty
In this code, we defined an empty array using the np.array() method and then used the flag approach whose value is boolean, and if it is True, then that means an array is empty; otherwise, it is not.
Testing an empty array converting into a list
To convert an array to a list in Python, use the tolist() method. The np.ndarray.tolist() function is used to convert an array into a list. Then using the len() function, we will count the number of elements of the list, and if it is equal to 0, then it means the array was empty before converting it.
import numpy as np emp_arr = np.array() if len(emp_arr.tolist()) == 0: print("The array is in fact empty") else: print("The array is not empty")
The array is in fact empty
Using arr.shape attribute
The arr.shape is an attribute of the numpy array that returns a tuple giving the shape of the array. First, we will check if the number of items in the 0th axis which is a row, and whether it is zero or not.
import numpy as np emp_arr = np.array() if emp_arr.shape == 0: print("The array is empty")
The array is empty
We got the 0th axis value 0, which means an array is empty.
Checking if an array is empty or not is an easy task, and we have gone through some of the approaches you can use.
That’s it for this tutorial.