+ 3

Logic behind Python slicing

Hi everyone, while doing some challenges, I came across a code that looked like this : x = [1, 3, 4, 5] print(x[:1:-1]) The output is [5, 4], and if we replace the -1 by -2, -3 or even -8500, the output will always be [5]. Can someone help me understand the logic behind this slicing please ? Thank you for your time

15th Sep 2020, 7:44 PM
Kvat Daniil
Kvat Daniil - avatar
2 ответов
+ 7
x[start:firstnot:step] start default is 0 or most left if step is negative. if step is <0 we go from right so start at 5 and firstnot is 3. step - 1: 4 as u mentioned [5,4] but step - 2:3 but 3 is already out of scope:[5] same for all steps - 2,-3,...,-5000
15th Sep 2020, 8:02 PM
Oma Falk
Oma Falk - avatar
+ 5
Thank you for the answers, it is very clear now !
15th Sep 2020, 8:07 PM
Kvat Daniil
Kvat Daniil - avatar