How to create a 3D array and print its strides using NumPy?
NumPy: Memory Layout Exercise-1 with Solution
Write NumPy program to create a 3D array of shape (2, 3, 4) and print its strides.
Sample Solution:
Python Code:
import numpy as np
# Create a 3D array of shape (2, 3, 4)
x = np.array([[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
# Print the strides of the array
print("Strides of the array:", x.strides)
Output:
Strides of the array: (48, 16, 4)
Explanation:
- Import NumPy: Import the NumPy library to handle array operations.
- Create 3D array x: Define a 3D array x with shape (2, 3, 4) containing integers.
- Print Strides: Print the strides of the array using the strides attribute.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy Memory Layout Exercises Home.
Next: How to reshape a 1D array into 2D and print Strides using NumPy?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/creating-a-3d-array-and-printing-its-strides-using-numpy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics