slice() function in Python is used to slice object of any type(string, bytes, tuple, list or range).

The general syntax for the round() function is

slice() Parameters

Python slice() function parameters
ParameterConditionDescription
startOptionalStarting index where the slicing of object starts.
Default is 0.
stopRequiredEnding index where the slicing of object stops.
stepOptionalAn optional argument that determines the increment between each index for slicing.
Default is 1.

Return Type: Returns a sliced object with specified range values.

When only one argument is passed then it is considered as the stop position for the slicing object and by default, slicing starts from 0th position with a step size of 1.

Let’s see some examples.

Examples

slice() function has returned the slice object with range values, so we need to use it as index for the list to get the sliced output list.

Note: The stop and start value are not restricted to the object’s bound, so you can even use negative or number exceeding the length of the iterable object’s length.

slice() with Negative Parameters

When we use negative values as the index in Python then it is considered as the position from the end.

In this example -7 points to 7th from last i.e ‘c’ and -2 as 2nd from the last i.e ‘g’.

When start and stop is specified as None and step as -1, then we get object in reverse order.

You can use slice to reverse a string or any iterable object using the above trick.

That’s all for slice() in Python, if you have any doubts or suggestions then please comment below.

Leave a Reply