Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python slice() function is used to slice a specified iterable. It has one required parameter which is used to specify stop location of slicing. Additionally, it has two optional parameters to specify start location of slicing and step size of slicing.

Syntax

slice(start, stop, size)
iterable[slice(start, stop, size)]

Parameters

start Optional. specify the location to start slicing. default is start of the iterable.
stop Required. specify the location to stop slicing.
size Optional. specify the step size of slicing.

Example:

In the below example, the slice() function is used on iterable called MyIterable to slice it in different way.

MyIterable = [0, 1, 2, 3, 4, 5, 6, 7]
NewIterable = slice(4)
print(MyIterable[NewIterable])

MyIterable = 'Learning Python'
NewIterable = slice(9, 15)
print(MyIterable[NewIterable])

MyIterable = list(range(0, 100, 10))
NewIterable = slice(0, 8, 2)
print(MyIterable[NewIterable])

The output of the above code will be:

[0, 1, 2, 3]

Python

[0, 20, 40, 60]

❮ Python Built-in Functions