'Python list slicing not working correctly [duplicate]

I have recently started learning python. After learning list slicing, I thought of trying it out. But when I am using -1, it's returning an empty list

numbers = [2, 3, 9, 5, 6, 0, 1]
# Slicing a list
print(numbers[1:5:-1])

gives, [ ] This video tells that -1 works: Here

Can you guys tell me why is it like that?



Solution 1:[1]

If you specify indices so that the start comes after the end, you always get an empty slice:

>>> numbers = [2, 3, 9, 5, 6, 0, 1]
>>> numbers[5:1]
[]

Putting -1 on the end reverses the slice, so you need to reverse the indices as well if you're doing it as part of the same slice:

>>> numbers[::-1]
[1, 0, 6, 5, 9, 3, 2]
>>> numbers[5:1:-1]
[0, 6, 5, 9]

This is the same as if you took the reverse slice on its own and then sliced it with [1:5] afterward:

>>> numbers[::-1][1:5]
[0, 6, 5, 9]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samwise