Python slice()
Python slice() class
The slice() class return a slice object representing the set of indices specified by range(start, stop, step).
Syntax
class slice(stop)
or
class slice(start, stop[, step])
Parameter
Start: This parameter represents an integer number specifying at which position to start the slicing, and by default, its value is 0.
Stop: This parameter represents an integer number specifying at which position to end the slicing.
Step: It is an optional parameter that represents an integer number specifying the step of the slicing.
Return
The slice() function returns a slice object.
Example 1
# Python program explaining # the slice() function #intializing the values n = ("A", "B", "C", "D", "E", "F", "G", "H") print("Value before slice function: ", n) slice_val = slice(6) print("Value after slice function: ", n[slice_val])
Output
Value before slice function: ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') Value after slice function: ('A', 'B', 'C', 'D', 'E', 'F', 'G')
Example 2
# Python program explaining # the slice() function # initializing the integer value valTup = (425,618,55,214,341,58,266) print("Initial values:",valTup) # the slice object slice1 = slice(0,10,3) # We can use this slice object to get elements strVal = valTup[slice1] # printing the siced value print("After the sliced value: ",strVal)
Output
Initial values: (425, 618, 55, 214, 341, 58, 266) After the sliced value: (425, 214, 266)