+ 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]

26th Jun 2020, 10:13 PM
Mohini Yadav
Mohini Yadav - avatar
6 ответов
+ 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.
26th Jun 2020, 10:40 PM
Seb TheS
Seb TheS - avatar
+ 3
Thank you guys Seb TheS , G B , 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 for the explanation. It helps me to understand more.
7th Jul 2020, 10:17 AM
Mohini Yadav
Mohini Yadav - avatar
+ 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]
26th Jun 2020, 10:24 PM
Slick
Slick - avatar
+ 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...
26th Jun 2020, 10:49 PM
G B
G B - avatar