Home > front end >  Python list slice [0:-1:-1]
Python list slice [0:-1:-1]

Time:07-24

I ran into this statement while I was coding:

l = [1,2,3]
print(l[0:-1:-1])

I was expecting this piece of code gives me [1] however it gives me [], makes me think I must have mis-understood python slice operation, can someone explain what is going on here?

CodePudding user response:

In a slice,

The first integer is the index where the slice starts.

The second integer is the index where the slice ends.

The third integer specifies a stride or step causing the resulting slice to skip items. -1 for reverse the output.

l[0:-1:-1] 

is equivalent to

l[len(l)-1:len(l)-1:-1]

The first index converted 0 to len(l)-1, because you added -1 in the last index to reverse the list. This will always give you an empty list.

CodePudding user response:

When you use slice in python and you type

l[x:y:-1]

it would somehow be equivalent to

l.reverse()
print(l[y:x])
l.reverse()

but with the difference that -1 reverses the list elements and their indexes so if you type

l=[1, 2, 3]
l[2:0:-1]

the output will be

[3, 2]

The reason for empty list is that you change the order of indexes so it wont find any element in that window...

  • Related