• In python slice () function is used to get a slice of elements from the collection of elements.
  • It provides two overloaded slice functions there the first takes a single argument while the second function takes three arguments and returns a slice object.
  • This slice object can be used to get a subsection of the collection.
  • Start parameter is used to starting index where the slicing of object starts.
  • Stop parameter is used to ending index where the slicing of objects stops.
  • Step parameter is an optional argument that determines the increment between each index for slicing.
  • It returns a sliced object containing elements in the given range only.

 

Sample Code

# Python slice() function example  

# Calling function  

tup = (45,68,955,1214,41,558,636,66)  

slic = slice(0,10,3) # returns slice object  

slic2 = slice(-1,0,-3) # returns slice object  

# We can use this slice object to get elements  

str2 = tup[slic]  

str3 = tup[slic2] # returns elements in reverse order  

# Displaying result  

print(str2)  

print(str3)

 

Output

Categorized in: