For a sequence , and two positions S and B within that sequence, the
expression E produces a new sequence
containing the elements of S between those two positions.
S [
B : E ]
>>> L [0, 1, 2, 3, 4, 5] >>> L[2] 2 >>> L[4] 4 >>> L[2:4] [2, 3] >>> s = 'abcde' >>> s[2] 'c' >>> s[4] 'e' >>> s[2:4] 'cd'
Note in the example above that the elements are selected
from position 2 to position 4, which does not include the element L[4].
You may omit the starting position to slice elements from at the beginning of the sequence up to the specified position. You may omit the ending position to specify a slice that extends to the end of the sequence. You may even omit both in order to get a copy of the whole sequence.
>>> L[:4] [0, 1, 2, 3] >>> L[4:] [4, 5] >>> L[:] [0, 1, 2, 3, 4, 5]
You can replace part of a list by using a slicing
expression on the left-hand side
of the “=” in an assignment
statement, and providing a list of replacement elements
on the right-hand side of the “=”. The elements selected by the slice are
deleted and replaced by the elements from the right-hand
side.
In slice assignment, it is not necessary that the number
of replacement elements is the same as the number of
replaced elements. In this example, the second and
third elements of L are replaced by the
five elements from the list on the right-hand side.
>>> L [0, 1, 2, 3, 4, 5] >>> L[2:4] [2, 3] >>> L[2:4] = [93, 94, 95, 96, 97] >>> L [0, 1, 93, 94, 95, 96, 97, 4, 5]
You can even delete a slice from a sequence by assigning an an empty sequence to a slice.
>>> L [0, 1, 93, 94, 95, 96, 97, 4, 5] >>> L[3] 94 >>> L[7] 4 >>> L[3:7] = [] >>> L [0, 1, 93, 4, 5]
Similarly, you can insert elements into a sequence by using an empty slice on the left-hand side.
>>> L [0, 1, 93, 4, 5] >>> L[2] 93 >>> L[2:2] = [41, 43, 47, 53] >>> L [0, 1, 41, 43, 47, 53, 93, 4, 5]
Another way to delete elements from a sequence is to use
Python's del statement.
>>> L [0, 1, 41, 43, 47, 53, 93, 4, 5] >>> L[3:6] [43, 47, 53] >>> del L[3:6] >>> L [0, 1, 41, 93, 4, 5]