numpy
  1. numpy-numpyempty

NumPy empty()

NumPy is a popular Python library used for working with arrays. The empty() function is one of the many built-in functions provided by NumPy that can be used to create an array of a specified shape and data type, without initializing elements to any value.

Syntax

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

Example

import numpy as np

# Create an empty 2D array of size 2x3 with float data type
arr = np.empty((2, 3), dtype=float)

print(arr)

Output

[[3.34830739e-316 6.36598737e-314 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000]]

Explanation

The empty() function creates a new array without initializing entries. By default, the newly created array contains random values based on the initial state of the memory allocated for the array. The function takes three arguments: shape, dtype, and order, of which only the shape argument is mandatory. dtype specifies the desired data type of the array, and order specifies the memory layout of the array.

Use

Typically, empty() is used when you need to create an array of a certain size, without needing to fill it with initial data. The uninitialized state of the empty() array makes it a faster option when compared to the other in-built array creation methods like zeros() and ones(), as it takes less time to generate a large array.

Important Points

  • The random values in the array are mostly dependent on the output of the system memory and are not guaranteed to be the same across different operating systems or computing platforms.
  • It is recommended to initialize NumPy arrays before using them to avoid uninitialized data in your computation.
  • Using empty() over other NumPy array-creation methods like zeros() or ones() can save some memory and processing time in specific cases.

Summary

In summary, empty() is a NumPy library function used to create a new array of a specified shape and data type without initializing the entries in the array. The created array is dependent on the initial state of the memory allocated, making it a faster option when compared to other in-built array creation functions. However, uninitialized data may be a potential risk while using this function, and so it is generally advised and preferred to initialize an array before using it in computations.

Published on: