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.

# Slice first 5 list items
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(5)
print(L[x])
# Prints ['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.

# Slice from index 2 to 7
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(2, 7)
print(L[x])
# Prints ['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.

# 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])
# Prints ['c', 'e', 'g']
Python slice() - Specifying Step Size

Slice with Negative Indices

You can specify negative indices while slicing a list.

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

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

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

You can even specify a negative step size.

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
x = slice(7, 2, -2)
print(L[x])
# Prints ['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.

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