Challenge - 5 Problems
np.empty() Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
np.empty() creates an array without setting values, so it contains whatever was in memory.
✗ Incorrect
np.empty() allocates memory for the array but does not initialize values, so the contents are random and depend on memory state.
❓ data_output
intermediate1: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)
Attempts:
2 left
💡 Hint
The shape is given by the first argument, and dtype is set explicitly.
✗ Incorrect
The array shape is (3,4) as specified, and dtype=int defaults to int64 on most 64-bit systems.
🔧 Debug
advanced2:00remaining
Why does np.empty() output contain unexpected values?
Consider this code:
Why does the output contain seemingly random numbers instead of zeros?
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)
Attempts:
2 left
💡 Hint
Think about what 'empty' means in this context.
✗ Incorrect
np.empty() allocates memory but does not set values, so the array contains whatever was previously in that memory location.
🚀 Application
advanced1: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()?
Attempts:
2 left
💡 Hint
Think about initialization cost.
✗ Incorrect
np.empty() is faster because it just allocates memory without setting values, useful when you will overwrite all values anyway.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
np.empty() behavior is the same regardless of dtype.
✗ Incorrect
np.empty() allocates memory for structured arrays but does not initialize the fields, so values are random.