In numpy, “empty” is an ambiguous term because an empty array means an array with zero elements or an uninitialized array with arbitrary memory content. It can have various shapes (0,), (0, n), or (m, 0, n)—as long as its total number of elements is zero.
Creating an empty array
The optimal method for creating a one-dimensional empty array is to use the np.array() function.
For a multidimensional empty array, the np.empty() function is more efficient.
Using np.array()
You can directly initialize an array with zero elements like this:
import numpy as np empty_array = np.array([]) print(empty_array) print(empty_array.shape) print(empty_array.size) # Output: # [] # (0,) # 0
The output is a one-dimensional array with no values. Its shape is (0,). This approach is direct and readable.
Using np.empty()
For creating a 2D or multidimensional empty array, the better approach is to use the “np.empty()” function.
Let’s define rows and columns for a 2D array:
import numpy as np arr2d = np.empty((0, 3)) # 0 rows and 3 columns print(arr2d) print(arr2d.size) print(arr2d.shape) # Output: # [] # 0 # (0, 3)
It is important to note that the np.empty() method sometimes fills the rows with 0s, and sometimes it does not fill the array with zeros but with arbitrary uninitialized values based on the operating system.
import numpy as np init_2d = np.empty((2, 3)) # 2 rows 3 columns print(init_2d) print(init_2d.size) print(init_2d.shape) # Output: # [[0. 0. 0.] # [0. 0. 0.]] # 6 # (2, 3)
For my macOS, it creates two rows and three columns of 0s. Your output might be different.
Let’s initialize a 3D empty array:
import numpy as np arr3d = np.empty((2, 0, 4)) # 2 rows 0 columns 4 depth print(arr3d) print(arr3d.size) print(arr3d.shape) # Output: # [] # 0 # (2, 0, 4)
Checking if a numpy array is empty
The most Pythonic way to check if an array is empty is to use the .size attribute. It returns the total number of elements in the array. If the size is 0, the array is empty; otherwise, it is not.
For 1D array
import numpy as np empty_array = np.array([]) if empty_array.size == 0: print("Array is empty") else: print("Array is not empty")
Output
Array is empty
For 2D array
For checking its emptiness, we can operate the .size attribute on it.
import numpy as np # Empty 2D array empty_2d_array = np.empty((0, 5)) # 0 rows, 5 columns print(f"Empty 2D array:\n{empty_2d_array}") if empty_2d_array.size == 0: print("The 2D array is empty (using .size)") # Non-empty 2D array non_empty_2d_array = np.array([[1, 2, 3], [4, 5, 6]]) print(f"\nNon-empty 2D array:\n{non_empty_2d_array}") if non_empty_2d_array.size == 0: print("The 2D array is empty (using .size)") else: print("The 2D array is NOT empty (using .size)")
Output
Empty 2D array: [] The 2D array is empty (using .size) Non-empty 2D array: [[1 2 3] [4 5 6]] The 2D array is NOT empty (using .size)
It is extremely efficient and the least complex way.