Issue
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
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]
Answered By - Samwise
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.