Python Tutorial Python Advanced Python References Python Libraries

Python slice() Function



The Python slice() function is used to slice a specified iterable. The function requires at least one parameter. If only one parameter is passed it is taken as specifying the location to stop slicing. Other two parameters can be used 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 Optional. specify the location to stop slicing. Default is end of the iterable.
size Optional. specify the step size of slicing. Default is 1.

Example:

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

MyList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#slicing Mylist from start to 5th element
list1 = MyList[slice(5)]
print("list1 contains:", list1)

#slicing Mylist from 5th element to 9th element
list2 = MyList[slice(4, 9)]
print("list2 contains:", list2)

#slicing Mylist from 7th element to last element
list3 = MyList[slice(6, None)]
print("list3 contains:", list3)

#slicing Mylist (alternate elements
#starting from start of the list)
list4 = MyList[slice(None, None, 2)]
print("list4 contains:", list4)

#slicing Mylist (alternate elements
#starting from 2nd element of the list)
list5 = MyList[slice(1, None, 2)]
print("list5 contains:", list5)

The output of the above code will be:

list1 contains: [0, 1, 2, 3, 4]
list2 contains: [4, 5, 6, 7, 8]
list3 contains: [6, 7, 8, 9, 10]
list4 contains: [0, 2, 4, 6, 8, 10]
list5 contains: [1, 3, 5, 7, 9]

Example:

Consider one more example where the slice() function is used with string and range iterable.

MyString = "Hello Python"

print("MyString contains:", MyString)
#slicing MyString from 7th element to last element
str = MyString[slice(6, None)]
print("str contains:", str)

x = list(range(0, 100, 10))

print("x contains:", x)
#slicing x (alternate elements
#starting from start of the list)
y = x[slice(None, None, 2)]
print("y contains:", y)

The output of the above code will be:

MyString contains: Hello Python
str contains: Python
x contains: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
y contains: [0, 20, 40, 60, 80]

❮ Python Built-in Functions