w3resource

How to create a 3D array and print its strides using NumPy?


1. 3D Array Strides Examination

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to create a 3D array of shape (2, 3, 4) and then use np.lib.stride_tricks.as_strided to generate a modified view with custom strides.
  • Write a NumPy program to compare the strides of a 3D array created in C order versus Fortran order.
  • Write a NumPy program to compute the memory offset manually from the strides of a 3D array and verify it with indexing.
  • Write a NumPy program to create two 3D arrays with identical shapes but different memory layouts and compare their strides.

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.



Follow us on Facebook and Twitter for latest update.