a = ["a", "b", "c", "d", "e", "f", "g", "h"]
print("Middle two: ", a[3:5])
print("All but ends: ", a[1:7])Middle two: ['d', 'e']
All but ends: ['b', 'c', 'd', 'e', 'f', 'g']
Python has syntax for slicing sequences
This is a method for accessing a subset of sequence elements
Slice is implemented by default for sequence types (list, tuple, str, bytes)
Slicing can be extended to any class implementing the __getitem__ and __setitem__ dunder methods
The basic syntax is a_sequence[start:end]
start is inclusiveend is exclusiveMiddle two: ['d', 'e']
All but ends: ['b', 'c', 'd', 'e', 'f', 'g']
0['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['e', 'f', 'g', 'h']
['f', 'g', 'h']
['c', 'd', 'e']
['c', 'd', 'e', 'f', 'g']
['f', 'g']
Slicing forward
['a', 'b', 'c', 'd', 'e']
['1', '2', '3']
Slicing backward
['d', 'e', 'f', 'g', 'h']
['1', '2', '3']
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[5], line 2 1 a = ["a", "b", "c", "d", "e", "f", "g", "h"] ----> 2 print(a[20]) IndexError: list index out of range
Indexing by a negated variable can lead to surprising results. E.g. the expression a[-n:] works for n>0, say n=3 a[-3:0]. When n is zero, a[-0:] evaluates to a[:] which slices the entire list
Before: ['d', 'e', 'f', 'g', 'h']
After: ['d', 99, 'f', 'g', 'h']
No change: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Shrinking a list with a slice
Before ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
After ['a', 'b', 99, 22, 14, 'h']
Growing a list with a slice
Before ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
After ['a', 'b', 47, 11, 'd', 'e', 'f', 'g', 'h']
[:][:] can be used to replace an entire list0 is the implicit start indexlen(sequence) is the implicit stop index