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(start,stop,step)

slice() Parameters

Python slice() function parameters
Parameter Condition Description
start Optional Starting index where the slicing of object starts.
Default is 0.
stop Required Ending index where the slicing of object stops.
step Optional An 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

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(5)
print(x)     
print(l[x])  
slice(None, 5, None)
['a', 'b', 'c', 'd', 'e']

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.

str = "Pencil Programmer"
x = slice(7)   
print(str[x]) 
"Pencil"
str = "Pencil Programmer"
x = slice(7,14)
print(str[x]) 
"Program"
str = "Pencil Programmer"
x = slice(7,None)
print(str[x])
"Programmer"

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.

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(-7, -2)
print(L[x])
['c', 'd', 'e', 'f', 'g']

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

L = ['p', 'e', 'n', 'c', 'i', 'l']
x = slice(None, None, -1)
print(L[x])  
['l', 'i', 'c', 'n', 'e', 'p']

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