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[:]




  1. The maximum value of upper is equal to the size of an array.
  2. If you don't specify lower, then by default the value is zero.
  3. If you don't 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[:])




Picture showing the output of Slice notation in NumPy for array

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:])




Picture showing the output of Slice notation in NumPy for matrics

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 27, 2019
 
Updated On  -  Tuesday, June 4, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250