Python - np.empty vs. np.zeros

2023. 2. 15. 22:37Data science/Python

반응형

When creating a new array of a given shape and typing in a programming language like Python, the values in the array are usually initialized to some default value. The default value can depend on the data type and language, but in Python, for example, the default value for a new array of integers is 0, and a new array of floats is a small, positive value close to 0.

np.zeros(10), by default - dtype=floats
The result of np.empty can be zeros or any random values

However, in some cases, we may not want the array entries to be initialized with any particular value, especially if we plan to fill in the entries with data later. In this case, we can create a new array without initializing the entries, meaning that the array's values will be undefined or random and may contain garbage values from memory.

np.empty(10)

Creating an array without initializing entries can be more efficient than creating an array with initialized entries, especially for large arrays, since it avoids the overhead of initializing the values. However, it is essential to remember that the values in the array will be unpredictable. The programmer must initialize the values before using them to avoid errors or unexpected results.

반응형