Python slice() Function

Returns a slice object to slice a sequence

Usage

The slice() function returns a slice object.

A slice object is used to specify how to slice a sequence (list, tuple, string or range etc.) .

You can specify where to start the slicing, where to stop and specify the step.

Syntax

slice(start,stop,step)

Python slice() function parameters
ParameterConditionDescription
startOptionalA number to specify start of the slicing.
Default is 0.
stopRequiredA number to specify end of the slicing.
stepOptionalA number to specify the step.
Default is 1.

slice(stop)

When you call slice() with just one argument, you can slice a sequence from index 0 up to the specified index.

Example: Slice first 5 list items

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(5)
print(L[x])		# ['a', 'b', 'c', 'd', 'e']
Python slice() - Specifying stop

Note that the item at index 5 ‘ f ‘ is not included.

slice(start, stop)

The slicing starts from 0 by default.

However, you can start the slice at another number by adding a start parameter.

Example: Slice from index 2 to 7

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(2, 7)
print(L[x]) 	# ['c', 'd', 'e', 'f', 'g']
Python slice() - Specifying start and stop

slice(start, stop, step)

The step of the slicing is 1 by default.

However, you can specify a different step size by adding a step parameter.

Example: Returns every 2nd item between position 2 to 7

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

Slice with Negative Indices

You can specify negative indices while slicing a list.

Example:

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

You can specify both positive and negative indices at the same time.

Example:

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

You can even specify a negative step size.

Example:

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

Reverse a Sequence

You can reverse a sequence by specifying both start and stop indices as ‘None‘ and a step as -1.

Example: Reverse a list with slice() function

L = ['a', 'b', 'c', 'd']
x = slice(None, None, -1)
print(L[x]) # ['d', 'c', 'b', 'a']