The slice()
function in Python is used to create a slice object that represents the set of indices specified by range(start, stop, step). The slice object can then be passed to a sequence to extract a part of the sequence.
Consider the following example:
In the above case, the slice object is created automatically when we pass the colon-separated range values to L in the square brackets. We can alternatively create a slice object then pass the object instead of the values themselves as shown below.
The slice function has the following syntax Syntax:
slice( stop, start = 0, step = 1)
stop | Specifies the position at which position to end the slicing. This argument is required. |
start | Specifies the position at which to start the slicing. It is optional and it defaults to 0. |
step | specifies the step of the slicing. It is also optional and defaults to 1. |
Note: All the three arguments, stop, start and step must be strictly integers.
The function returns a slice object based on the given arguments.
Let us see some more examples: