w3resource

Python: Creating multidimensional arrays with unspecified dimensions


6. Ellipsis in Multidimensional Array

Write a Python program that uses 'Ellipsis' to create a multidimensional array with unspecified dimensions.

Sample Solution:

Code:

import numpy as np
# Create a multidimensional array with unspecified dimensions
nums = np.array([[[1, 2], [3, 4]], [..., ...], [[5, 6], [7, 8]]])
# Print the array
print(nums)

Output:

[[list([1, 2]) list([3, 4])]
 [Ellipsis Ellipsis]
 [list([5, 6]) list([7, 8])]]

In the exercise above, we use 'ellipsis (...)' to represent unspecified dimensions in a NumPy array. The resulting array contains 'ellipsis' as placeholders for dimensions not explicitly specified. In this way, we can create multidimensional arrays without having to specify all dimensions in advance.

Flowchart:

Flowchart: Python: Creating multidimensional arrays with unspecified dimensions.

For more Practice: Solve these Related Problems:

  • Write a Python program to create a NumPy array and then use Ellipsis in slicing to extract a subarray that includes all dimensions except the first.
  • Write a Python script to demonstrate the use of Ellipsis in indexing a 4D NumPy array to obtain a 2D slice.
  • Write a Python function that takes a multidimensional NumPy array and returns a slice from the second dimension onward using Ellipsis.
  • Write a Python program to create a 3D NumPy array and use Ellipsis to select all elements in the last two dimensions, then print the result.

Python Code Editor :

Previous: Python Program: Checking and handling ellipsis in variables.
Next: Generating sequences with ellipsis in Python.

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.