Slicing extracts a portion of a Python list or string with [start:stop]: the start is included and the stop is excluded. Omit start to begin at the sequence’s beginning, or stop to continue to its end. Negative indices count from the end; a stop before the start produces an empty list. section 5.2 section 6.1
Common list-slicing uses include:
- Extract a portion, as in x[1:-1], or make a shallow list copy with x[:]. section 5.2
- Replace, insert, or remove a region with slice assignment; the list can grow or shrink to fit the replacement. section 5.3
- Extract a string substring, such as x[:-1] to remove a trailing newline from the result; strings themselves cannot be modified. section 6.1
Replace a list region
Starting with x = [1, 2, 3, 4, 5], assigning x[1:3] = [8, 9, 10] replaces 2 and 3, leaving [1, 8, 9, 10, 4, 5]. section 5.3
x = ["first", "second", "third", "fourth"] x[0] #1 'first' #1 x[2] #1 'third' x[-1] #2 'fourth' #2 x[-2] #2 'third' #2 x[1:-1] #2 ['second', 'third'] #3 x[0:3] #3 ['first', 'second', 'third'] #3 x[-2:-1] #3 ['third'] #3 x[:3] #3 ['first', 'second', 'third'] #4 x[-2:] #4 ['third', 'fourth'] #4 #1 Index from the front using positive index starting from 0 #2 Index from the back using negative index (–1 is the last element) #3 A slice[m:n], where m is the starting point and n is the exclusive ending point #4 The slice starts at its beginning (m) and goes to list’s end.
See positive and negative indices alongside slices with omitted bounds. section 3.2.2















