Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is list[-1:1] empty in python?

Tags:

python

list

>>>list=[1,2,3]  
>>>list[1:2]  
2  
>>>list[-1:1]  
[]  

In python, list[first:last] is return list[first,first+1,...last-1]
but list[-1:1] is return empty, why not include list[-1]?

like image 328
minssi Avatar asked Feb 10 '26 17:02

minssi


1 Answers

What are you expecting to return? Your -1 position in that list is 2, so your list[-1:1] is the same as list[2:1] which is empty list. You could do it with step=-1:

list[-1:1:-1]
3

Note: Usually it's not a good idea to reassign built-in variables such as list. It's better to use some othe name, i.e. l:

l = [1,2,3]

l[1]
2

l[-1]
3

l[-1:1]
[]

l[-1:1:-1]
[3]
like image 184
Anton Protopopov Avatar answered Feb 12 '26 06:02

Anton Protopopov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!