Articles → Numpy → Slice Notation In Numpy
Slice Notation In Numpy
What Is Slice Notation?
Syntax
Array_object[lower:upper]
Or
Array_object[:upper]
Or
Array_object[lower:]
Or
Array_object[:]
- The maximum value of the upper is equal to the size of an array.
- If you do not specify lower, then by default the value is zero.
- If you do not specify upper, then by default the value is equal to the length of the array.
Example
import numpy as np
arr = np.arange(0,10)
# The value is displayed from position 1 to 5
print ("Value from position 1 to 5 is: ", arr[1:5])
# The value is displayed from position 0 to 5. Here we don't specify the lower.
print ("Value from position 0 to 5 is: ", arr[:5])
# The value is displayed from position 5 to 10
print ("Value from position 5 to 10 is: ", arr[5:])
# Display all the elements
print ("Display all the elements", arr[:])
Click to Enlarge
Slice Notation In Matrices
import numpy as np
my_matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
# single bracket approach
print(my_matrix[0,1:])
# double bracket approach
print(my_matrix[0][1:])
Output
Click to Enlarge