Slicing in python
Goal
A slicing selects a range of items in a sequence object (e.g., a string, tuple or list).
General syntax
a[start:stop]
: from start
through stop-1
a[start:]
: from start
through the end of the array
a[:stop]
: from the beginning through stop-1
a[:]
: the whole array
The negative syntax
With sequences, we can use negative syntax such as:
a[-1]
: last item in the array
In the slicing location, we can also use this syntax.
start
or stop
may be a negative number, which means it counts from the
end of the array instead of the beginning.
example:
a[:-1]
: All but the last element
a[1:-1]
: From the second element to the before last element
a[-2:]
: last two items
a[:-5]
: All but the last 5 items