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











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





Click to Enlarge


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250