+ 2
I am confused When we do list slicing, can we use first value negative? If not then why? Can someone please explain this to me?
Eg. List=[0,2,4,7,8,9,5,7,1] Slice= List[-2:1:1]
6 Respostas
+ 5
Yes, any of the values can be negative.
List[-2:1:1] is a shortcut for List[len(List) - 2:1:1].
Because it tells to slice from index 7 (9-2) to index 1 with the step of 1, which is impossible, the slicing gives an empty list.
+ 3
+ 1
the syntax is: list[start, stop, step]
if you want to go backwards, lets try from the code you provided.
List[5:0:-1]
# output
[8, 7, 4, 2]
+ 1
When slicing, the last number gives the step. If it is positive, it goes from left to right, if it is negative, it goes from right to left...
List[-2:1:-1] #output [7,5,9,8,7,4]
List[-5:-2:1] #output[8,9,5]
these are also possible , when first number is negative...