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.Slice notation is
[start:stop:step]
. This means "begin atstart
, then increase bystep
until you get toend
." It's similar to this construct:This will produce, as expected,
0
through9
.Now imagine if we tried it with the values you're using:
If we actually executed this, it would print
2
, then add-1
to that to get1
, then print1
and add-1
to that to get0
, 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
orstop
empty, as in[:4]
or[::-1]
, this indicates the beginning or end of the sequence, as determined by thestep
. Python will go forwards with a positivestep
and backwards with a negativestep
(trying to use astep
of0
produces an error).If you specify a
start
,end
, andstep
that couldn't work (an emptystep
defaults to1
), Python will simply return an empty sequence.