l[start:end]
l[start:end]
where l is some collection, start is an inclusive index, and end is an exclusive index.
In [1]: l = list(range(10))
In [2]: l[:5] # firstFirst five elements
Out[2]: [0, 1, 2, 3, 4]
In [3]: l[-5:] # lastLast five elements
Out[3]: [5, 6, 7, 8, 9]
When slicing from the start, you can omit the zero index, and when slicing to the end, you can omit the final index since it is redundant, so do not be verbose:
In [7]: l[:-1] # includeInclude all elements but the last one
Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
In [8]: l[-3:] # takeTake the last 3three elements
Out[8]: [7, 8, 9]
In [9]: l[:20] # 20 is out of index bounds, and l[20] will raise an IndexError exception
Out[9]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: l[-20:] # -20 is out of index bounds, and l[-20] will raise an IndexError exception
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Keep in mind that the result of slicing a collection is a whole new collection. In addition, when using slice notation in assignments, the length of the slice assignmentassignments do not need to be the same. The values before and after the assigned slice will be kept, and the collection will shrink or grow to contain the new values:
In [16]: l[2:6] = list('abc') # assigningAssigning lessfewer elements than the ones contained in the sliced collection l[2:6]
In [17]: l
Out[17]: [0, 1, 'a', 'b', 'c', 6, 7, 8, 9]
In [18]: l[2:5] = list('hello') # assigningAssigning more elements than the ones contained in the sliced collection l [2:5]
In [19]: l
Out[19]: [0, 1, 'h', 'e', 'l', 'l', 'o', 6, 7, 8, 9]
In [22]: l = list(range(10))
In [23]: l[::2] # takeTake the elements which indexes are even
Out[23]: [0, 2, 4, 6, 8]
In [24]: l[1::2] # takeTake the elements which indexes are odd
Out[24]: [1, 3, 5, 7, 9]
However, using a negative value for step could become very confusing. Moreover, in order to be PythonicPythonic, you should avoid using start, end, and step in a single slice. In case this is required, consider doing this in two assignments (one to slice, and the other to stride).
In [29]: l = l[::2] # thisThis step is for striding
In [30]: l
Out[30]: [0, 2, 4, 6, 8]
In [31]: l = l[1:-1] # thisThis step is for slicing
In [32]: l
Out[32]: [2, 4, 6]