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
Slice notation in short:
[ : : ]
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
No comments:
Post a Comment