Reversing a list using slice notation

user737079 picture user737079 · May 4, 2011 · Viewed 69.8k times · Source

in the following example:

foo = ['red', 'white', 'blue', 1, 2, 3]

where: foo[0:6:1] will print all elements in foo. However, foo[6:0:-1] will omit the 1st or 0th element.

>>> foo[6:0:-1]
[3, 2, 1, 'blue', 'white']

I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?

Answer

Andrew Clark picture Andrew Clark · May 4, 2011

Slice notation in short:

[ <first element to include> : <first element to exclude> : <step> ]

If you want to include the first element when reversing a list, leave the middle element empty, like this:

foo[::-1]

You can also find some good information about Python slices in general here:
Explain Python's slice notation