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
list[::-1]
I learned this years ago but never thought about it until reviewing just now. Why is it
[::-1]
? Does the first colon(:) mean we start at the beginning, and the second colon(:) mean we end also at the beginning?
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
How do I reverse a part (slice) of a list in Python? - Stack Overflow
reverse - Reversing a list slice in python - Stack Overflow
Reversing a list using slice
why can't I remove the last element of an array and reverse it this way?
Videos
Just use the slice and reverse it.
a[2:4] = a[2:4][::-1]
a[2:4] creates a copy of the selected sublist, and this copy is reversed by a[2:4].reverse(). This does not change the original list. Slicing Python lists always creates copies -- you can use
b = a[:]
to copy the whole list.
The syntax is always [start:end:step] so if you go backwards your start needs to be greater than the end. Also remember that it includes start and excludes end, so you need to subtract 1 after you swap start and end.
l[5:2:-1]= [6, 5, 4]
l[4:1:-1]= [5, 4, 3]
Slice notation is [start:stop:step]. This means "begin at start, then increase by step until you get to end." It's similar to this construct:
counter = 0
stop = 10
step = 1
while counter < stop:
print(counter)
counter += step
This will produce, as expected, 0 through 9.
Now imagine if we tried it with the values you're using:
counter = 2
stop = 5
step = -1
while counter < stop:
print(counter)
counter += step
If we actually executed this, it would print 2, then add -1 to that to get 1, then print 1 and add -1 to that to get 0, then it would be -1, -2, and so on, forever. You would have to manually halt execution to stop the infinite loop.
If you leave start or stop empty, as in [:4] or [::-1], this indicates the beginning or end of the sequence, as determined by the step. Python will go forwards with a positive step and backwards with a negative step (trying to use a step of 0 produces an error).
>>> l[2::]
[3, 4, 5, 6, 7, 8]
>>> l[2::-1]
[3, 2, 1]
>>> l[:2:]
[1, 2]
>>> l[:2:-1]
[8, 7, 6, 5, 4]
If you specify a start, end, and step that couldn't work (an empty step defaults to 1), Python will simply return an empty sequence.