Python | slice constructor
Start your free 7-days trial now!
Python's slice(~)
constructor returns a slice object that usually contains a portion of a sequence.
Parameters
1. start
| integer
| optional
The start position for the slice object (inclusive). Defaults to 0
.
2. stop
| integer
The stop position for the slice object (non-inclusive).
3. step
| integer
| optional
Increment for each integer in the sequence. Defaults to 1
.
Although we can use slice(start, stop, step)
notation, the most common notation is indexing syntax sequence[start:stop:step]
.
Return value
A slice object that usually contains a portion of a sequence.
Examples
Basic usage
To create a slice object from start position 0
to stop position 5
:
numbers = [0, 1, 2, 3, 4, 5]slice_object = slice(5)s1 = numbers[slice_object]s2 = numbers[:5]print(s1)print(s2)
[0, 1, 2, 3, 4][0, 1, 2, 3, 4]
We can see that both notation forms yield the same result.
Start parameter
To specify the start of the slice:
numbers = [0, 1, 2, 3, 4, 5]print(numbers[1:5])
[1, 2, 3, 4]
We can see that the resulting slice begins at value of index position 1
of numbers
.
Step parameter
To specify the step of the slice:
numbers = [0, 1, 2, 3, 4, 5]print(numbers[1:6:2])
[1, 3, 5]
From start value of 1
, we increment by 2
until we reach the stop value of 6
.
Negative Index
To specify negative start
, stop
and step
:
letters = ('S', 'k', 'y', 'T', 'o', 'w', 'n', 'e', 'r')print(letters[-1:-5:-1])
('r', 'e', 'n', 'w')
By specifying start of -1
we start at the last element of the tuple, ad a step of -1
means we work backwards by one index position increment at a time until index position -5
(fifth to last element in original tuple).