Skip to content

Instantly share code, notes, and snippets.

@delwar2016
Last active January 10, 2017 01:59
Show Gist options
  • Save delwar2016/4aa3b0228761661527db9fb17cb87aac to your computer and use it in GitHub Desktop.
Save delwar2016/4aa3b0228761661527db9fb17cb87aac to your computer and use it in GitHub Desktop.
Explain Python's slice notation
array[start:end:step] # start through not past end, by step
start: the beginning index of the slice, it will include the element at this index unless it is the same as end, defaults to 0, i.e. the first index.
If it's negative, it means to start n items from the end.
end: the ending index of the slice, it does not include the element at this index,
defaults to length of the sequence being sliced, that is, up to and including the end.
step: the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse.
The key point to remember is that the :end value represents the first value that is not in the selected slice.
So, the difference beween end and start is the number of elements selected (if step is 1, the default).
The other feature is that start or end may be a negative number,
which means it counts from the end of the array instead of the beginning.
So:
array[-1] # last item in the array
array[-2:] # last two items in the array
array[:-2] # everything except the last two items
Python is kind to the programmer if there are fewer items than you ask for.
For example, if you ask for array[:-2] and array only contains one element, you get an empty list instead of an error.
Sometimes you would prefer the error, so you have to be aware that this may happen.
Source:
http://stackoverflow.com/questions/509211/explain-pythons-slice-notation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment