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?
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
Create a slice that starts at the end of the string, and moves backwards. In this particular example, the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1 , negative one, which means one step backwards.
You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.
Why Use [:-1] The slice operator [:-1] is a shorthand expression to produce a result from an original string or list variable to remove the last character in a string or last element in a list. The slice operation will not mutate (permanently change) the original string or list variable.
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
If you are having trouble remembering slice notation, you could try doing the Hokey Cokey:
[In: Out: Shake it all about]
[First element to include: First element to leave out: The step to use]
YMMV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With