3
>>>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]?

2 Answers 2

11

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]
Sign up to request clarification or add additional context in comments.

1 Comment

"usually" is an understatement :D
0

in list[first,last]... the order matters

list=[1,2,3,4,5,6]

if we try list[4,2] first = 4 and last = 2...(error..!!!!!) it returns []

u can use

>>> list=[1,2,3,4,5,6]
>>> list[::-1]
[6, 5, 4, 3, 2, 1]
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.