0
0
NumPydata~5 mins

np.empty() for uninitialized arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.empty() to create a new array quickly without setting values. It helps when you want to fill the array later and don't need initial values.

When you want to create an array to fill with data later.
When you need a fast way to allocate memory for an array.
When initial values do not matter and you want to save time.
When you want to create a placeholder array for calculations.
When you want to avoid the overhead of initializing values like zeros or ones.
Syntax
NumPy
import numpy as np

array = np.empty(shape, dtype=float, order='C')

shape is the size of the array you want, like (3, 4) for 3 rows and 4 columns.

dtype sets the type of data, like float or int. Default is float.

Examples
This creates a 2 by 3 array with uninitialized float values. The values will be random garbage data.
NumPy
import numpy as np

# Create an empty 2x3 array of floats
empty_array = np.empty((2, 3))
print(empty_array)
This creates a 1D array of 5 integers with uninitialized values.
NumPy
import numpy as np

# Create an empty 1D array with 5 integers
empty_int_array = np.empty(5, dtype=int)
print(empty_int_array)
This creates an empty array with zero elements. It is valid but has no data.
NumPy
import numpy as np

# Create an empty array with zero size
empty_zero = np.empty(0)
print(empty_zero)
Sample Program

This program creates an empty 3 by 2 array with uninitialized values. It prints the array first to show random data. Then it fills the array with numbers based on row and column indexes and prints the updated array.

NumPy
import numpy as np

# Create an empty 3x2 array
empty_array = np.empty((3, 2))
print("Array before filling:")
print(empty_array)

# Fill the array with values
for row_index in range(empty_array.shape[0]):
    for col_index in range(empty_array.shape[1]):
        empty_array[row_index, col_index] = row_index * 10 + col_index

print("\nArray after filling:")
print(empty_array)
OutputSuccess
Important Notes

Time complexity: Creating an empty array is very fast, O(1) for allocation.

Space complexity: Uses memory proportional to the array size.

Common mistake: Expecting np.empty() to initialize values to zero. It does not initialize; values are random garbage.

Use np.empty() when you plan to fill the array yourself. Use np.zeros() or np.ones() if you need initialized values.

Summary

np.empty() creates arrays without setting initial values.

It is useful for fast memory allocation when you will fill the array later.

Values in the array before filling are random and should not be used.