In this article, we will see how to use the ellipsis slicing syntax in Python.
Before understanding ellipsis slicing, it is important to understand the slicing concept in Python. Slicing is used to extract a portion of an array or a sequence. It provides a mechanism to get specific elements by using the starting, ending and optional step values.
Following is the syntax of slicing in Python:
sequence[start:end:step]
The start value in the above example is inclusive whereas the end is exclusive. The step determines the distance between elements.
Ellipses syntax
The ellipses syntax is represented by “…” which is mainly used during the slicing operations of the multi-dimensional arrays or sequences.
We can also use ellipses along with multiple colons “:” to indicate all dimensions in a particular axis.
The ellipsis can be used in place of multiple colons (“:”) to indicate that all dimensions in a particular axis should be selected. This allows for more compact and readable code, especially when dealing with large and complex arrays.
In the following example, we selected all the rows and columns in a 2D array using the ellipses syntax (…)
import numpy as np
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Select all rows, second column
result = array[..., 1]
print(result) # Output: [2 5 8]
# Select second row, all columns
result = array[1, ...]
print(result) # Output: [4 5 6]
In the following example, we are slicing along multiple axes in a 3D array.
import numpy as np
array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Select all elements in the first axis (depth)
result = array[..., :]
print(result)
"""
Output:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
"""
# Select second row in the first axis (depth)
result = array[1, ...]
print(result)
"""
Output:
[[5 6]
[7 8]]
"""