I am trying to reverse slice of a list in python but it returns an empty list. But when I try with whole list, it works fine. Am I missing anything here?
l=[1,2,3,4,5,6,7,8]
l[::-1]=[8, 7, 6, 5, 4, 3, 2, 1] <<< This worked fine.
l[2:5]=[3, 4, 5]
l[2:5:-1]=[] <<< Expecting [5,4,3] here.
Any clues?
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.