0
0
NumPydata~20 mins

np.empty() for uninitialized arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
np.empty() Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.empty() with shape (2,2)
What is the output of the following code?
import numpy as np
arr = np.empty((2,2))
print(arr)
NumPy
import numpy as np
arr = np.empty((2,2))
print(arr)
AA 2x2 array with uninitialized random values
BA 2x2 array filled with zeros
CA 2x2 array filled with ones
DRaises a TypeError
Attempts:
2 left
💡 Hint
np.empty() creates an array without setting values, so it contains whatever was in memory.
data_output
intermediate
1:30remaining
Shape and dtype of np.empty array
What will be the shape and data type of the array created by this code?
import numpy as np
arr = np.empty((3,4), dtype=int)
print(arr.shape, arr.dtype)
NumPy
import numpy as np
arr = np.empty((3,4), dtype=int)
print(arr.shape, arr.dtype)
A(4, 3) float64
B(3, 4) int64
C(3, 4) float64
D(4, 3) int32
Attempts:
2 left
💡 Hint
The shape is given by the first argument, and dtype is set explicitly.
🔧 Debug
advanced
2:00remaining
Why does np.empty() output contain unexpected values?
Consider this code:
import numpy as np
arr = np.empty(5)
print(arr)

Why does the output contain seemingly random numbers instead of zeros?
NumPy
import numpy as np
arr = np.empty(5)
print(arr)
Anp.empty() does not initialize the array, so it contains leftover memory values
Bnp.empty() initializes the array with zeros but print shows garbage
Cnp.empty() creates an array of None values
Dnp.empty() raises an error if not initialized
Attempts:
2 left
💡 Hint
Think about what 'empty' means in this context.
🚀 Application
advanced
1:30remaining
Using np.empty() for performance
You want to create a large array to fill with calculated values later. Which is the best reason to use np.empty() instead of np.zeros()?
Anp.empty() validates input data types
Bnp.empty() automatically fills with zeros
Cnp.empty() uses less memory than np.zeros()
Dnp.empty() is faster because it skips initializing values
Attempts:
2 left
💡 Hint
Think about initialization cost.
🧠 Conceptual
expert
2:30remaining
Behavior of np.empty() with structured dtypes
What will be the output of this code?
import numpy as np
dtype = [('x', 'i4'), ('y', 'f4')]
arr = np.empty(2, dtype=dtype)
print(arr)
NumPy
import numpy as np
dtype = [('x', 'i4'), ('y', 'f4')]
arr = np.empty(2, dtype=dtype)
print(arr)
ARaises a TypeError due to structured dtype
BAn array of zeros with integer and float fields
CAn array of 2 elements with uninitialized integer and float fields
DAn array filled with None values
Attempts:
2 left
💡 Hint
np.empty() behavior is the same regardless of dtype.