Python: Understanding Slice Notation

In my mind the easiest way to understand Python's slice notation is to visualize it with real examples. Once you get it under your fingers you'll find list slicing is an invaluable tool to have in your Python toolkit.

>>> menu = ['eggs', 'sausage', 'bacon', 'tomato', 'spam'] >>> print(menu[0]) eggs >>> print(menu[-1]) spam >>> print(menu[0:1]) ['eggs'] >>> print(menu[0:3]) ['eggs', 'sausage', 'bacon'] >>> print(menu[1:3]) ['sausage', 'bacon'] >>> print(menu[1:-1]) ['sausage', 'bacon', 'tomato'] >>> print(menu[:-1]) ['eggs', 'sausage', 'bacon', 'tomato'] >>> print(menu[:-2]) ['eggs', 'sausage', 'bacon'] >>> print(menu[:2]) ['eggs', 'sausage'] >>> print(menu[:3]) ['eggs', 'sausage', 'bacon'] >>> print(menu[::2]) ['eggs', 'bacon', 'spam'] >>> print(menu[::3]) ['eggs', 'tomato'] >>> print(menu[::-1]) ['spam', 'tomato', 'bacon', 'sausage', 'eggs']

From the Python docs we have:

menu[start:stop:step]

where start is 0-based from the beginning, stop is stop - 1 and step is how many items we move forward each step (default being 1). You can also use negative numbers for start and stop to indicate the end of the string instead of the beginning. Finally you can use a negative in the step position to reverse the output.

Good luck and happy slicing!

-Sethers