0
0
NumPydata~20 mins

Understanding array memory layout in NumPy - Practice Questions & Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of array strides in NumPy

What is the output of the following code showing the strides of a 2D NumPy array?

NumPy
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
print(arr.strides)
A(12, 4)
B(3, 1)
C(8, 4)
D(4, 12)
Attempts:
2 left
💡 Hint

Remember that strides show the number of bytes to step in each dimension.

data_output
intermediate
2:00remaining
Effect of transpose on array strides

What is the output of the strides attribute after transposing the array?

NumPy
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
arr_t = arr.T
print(arr_t.strides)
A(4, 12)
B(12, 4)
C(3, 1)
D(8, 4)
Attempts:
2 left
💡 Hint

Transposing swaps the dimensions and their strides.

visualization
advanced
2:30remaining
Visualizing memory layout of a reshaped array

Which option correctly describes the memory layout visualization of the following reshaped array?

NumPy
import numpy as np
arr = np.arange(6, dtype=np.int32)
arr_reshaped = arr.reshape((2, 3))
print(arr_reshaped.strides)
AThe array is stored non-contiguously with gaps between elements.
BThe array is stored with strides (4, 12), columns stored one after another.
CThe array is stored in a contiguous block with strides (12, 4), rows stored one after another.
DThe array is stored in Fortran order with strides (4, 8).
Attempts:
2 left
💡 Hint

Check the strides and how reshape affects memory layout.

🧠 Conceptual
advanced
2:00remaining
Understanding C-contiguous vs F-contiguous arrays

Which statement correctly describes the difference between C-contiguous and F-contiguous arrays in NumPy?

AC-contiguous arrays are always 1D; F-contiguous arrays are always 2D.
BC-contiguous arrays store columns sequentially; F-contiguous arrays store rows sequentially.
CBoth C-contiguous and F-contiguous arrays store data randomly in memory.
DC-contiguous arrays store rows sequentially in memory; F-contiguous arrays store columns sequentially.
Attempts:
2 left
💡 Hint

Think about how multi-dimensional arrays are stored in C and Fortran languages.

🔧 Debug
expert
2:30remaining
Identifying cause of unexpected array memory layout

Given the code below, why does arr.flags['C_CONTIGUOUS'] return False?

NumPy
import numpy as np
arr = np.arange(12).reshape((3,4))
arr_sliced = arr[:, ::2]
print(arr_sliced.flags['C_CONTIGUOUS'])
ABecause the array dtype is not compatible with C-contiguity.
BBecause slicing with a step creates a non-contiguous view in memory.
CBecause the array has only one dimension.
DBecause reshape always returns a non-contiguous array.
Attempts:
2 left
💡 Hint

Consider how slicing with steps affects memory layout.