In Python, expressions can be written that select subsections of a sequence, known as slices. A slice is a span of items that are taken from a sequence.
To get a slice of a list, you write an expression in the following general format:
list_name[start : end]
In the general format, start is the index of the first element in the slice, and end is the index marking the end of the slice. The expression returns a list containing a copy of the elements from start up to (but not including) end.
>>> numbers = [1, 2, 3, 4, 5]
>>>
print(numbers)
[1,
2, 3, 4, 5]
>>>
print(numbers[1:3])
[2,
3]
>>>
print(numbers[:3])
[1,
2, 3]
>>>
print(numbers[2:])
[3,
4, 5]
>>>
print(numbers[:])
[1,
2, 3, 4, 5]
Slicing
expressions can also have step value, which can cause elements to be skipped in
the list.
The
following interactive mode session shows an example of a slicing expression
with a step value:
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
print(numbers)
[1,
2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
print(numbers[1:8:2])
[2,
4, 6, 8]
In
the slicing expression, the third number inside the brackets is the step value.
A step value of 2, as used in this example, causes the slice to contain every
second element from the specified range in the list.
Negative numbers are used as indexes in slicing expressions to reference positions relative to the end of the list.
Note: Invalid indexes do not cause slicing expressions to raise an exception.
For
example:
• If the end index specifies a
position beyond the end of the list, Python will use the
length of the list instead.
• If the start index specifies a
position before the beginning of the list, Python will
use 0 instead.
• If the start index is greater
than the end index, the slicing expression will return
an empty list.