Python Function: Slicing the third dimension of a multidimensional array
3. Multidimensional Array Slicer
Write a Python function that takes a multidimensional array and slices the first two elements from the third dimension.
Sample Solution:
Code:
import numpy as np
def slice_third_dimension(arr):
"""
Args:
arr (numpy.ndarray): The input multidimensional array.
Returns:
numpy.ndarray: The sliced array.
"""
return arr[..., :2]
# Example usage:
nums = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
[[13, 14, 15], [16, 17, 18]]])
print("Original multidimensional array:")
print(nums)
sliced_array = slice_third_dimension(nums)
print("\nSlices the first two elements from the said array:")
print(sliced_array)
Output:
Original multidimensional array: [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]] [[13 14 15] [16 17 18]]] Slices the first two elements from the said array: [[[ 1 2] [ 4 5]] [[ 7 8] [10 11]] [[13 14] [16 17]]]
In the exercise above, the "slice_third_dimension()" function takes a NumPy multidimensional array as input and uses the ellipsis (...) to slice the first two elements from the third dimension. In the resulting sliced array, only the first two elements of the third dimension are preserved.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python function that accepts a 3D NumPy array and returns a slice containing only the first two elements from the third dimension.
- Write a Python script to generate a random 4D array, slice out the first two elements from the third axis of each sub-array, and print the modified array.
- Write a Python program that takes a multidimensional array and prints the shape of the array after slicing the first two elements of its third dimension.
- Write a Python function that, given a 3D list, extracts the first two items from the innermost lists and returns the resulting structure.
Python Code Editor :
Previous: Python Function: Calling functions with flexible arguments.
Next: Python Program: Creating lists with gaps using ellipsis.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.