Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List slicing with negative step size

Tags:

python

Why does the below code returns an empty list when it should return [4, 3, 2] (because of the negative step size):

i = [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
   #[  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
   #[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
s = i[2:-5:-1]
print(s)
like image 238
Akshay J Avatar asked Oct 19 '25 17:10

Akshay J


1 Answers

It starts counting from "2" going backwards (step -1) until "-5" is reached - but reaching the element "-5" would require positive step in this case.

For example the output of:

i[2::-1]

is: [2, 1, 0]

like image 59
Lemurata Avatar answered Oct 22 '25 07:10

Lemurata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!