Slicing in Python - howto access parts in strings, tuples, lists etc
Inspiration from: https://stackoverflow.com/questions/509211/understanding-slice-notation
Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. Slices can also be applied on third-party objects like NumPy arrays, as well as Pandas series and data frames.
a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array
You could also add a valid step when you slice
a[start:stop:step] # start through not past stop, by step
The start or stop may be a negative number, which means it counts from the end of the array instead of the beginning.
a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items
Similarly, step may be a negative number:
a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed