+ 2

Question about List Slices

Hello dear community, Why squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[:1:-1]) Output: [81, 64, 49, 36, 25, 16, 9, 4] But squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[0:1:-1]) Output: [] Aren’t these print statements equal?

22nd Sep 2022, 7:25 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
8 Answers
+ 8
Nope Actually the first one is [-1:1:-1] With a negative step(3rd value) u should go right to left, otherwise the result is empty. The default first value is -1 in this case.
22nd Sep 2022, 7:44 AM
Oma Falk
Oma Falk - avatar
+ 5
Ruslan Guliyev defaults: going forward the first value is most left, Going backwards the first value is most right It is straightforward.
22nd Sep 2022, 8:53 AM
Oma Falk
Oma Falk - avatar
+ 4
No! print(squares[:1:-1]) identical to this: print(squares[len(squares):1:-1])
22nd Sep 2022, 8:07 AM
Solo
Solo - avatar
+ 3
First list: As we know squares[start:end:step] , first list [:1:-1] your list will start in the end because you let the step equal -1 to the index 1 . Is simply equal to squares [len(squares): 1 : -1] the end is not included.
23rd Sep 2022, 11:31 AM
Oussama Harmouche
Oussama Harmouche - avatar
+ 2
Oma Falk But why is the first value converted to -1? Is it just a rule that I need to memorize or there is some logic behind it?
22nd Sep 2022, 8:26 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
+ 2
#index: 0, 1, 2, 3... values = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] #index:-10,-9,-8,-7...
22nd Sep 2022, 10:06 AM
Solo
Solo - avatar
+ 2
Oma Falk Solo Thanks a lot for your answers!
22nd Sep 2022, 11:36 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
0
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[:1:-1]) print(squares[-1:1:-1]) print(squares[len(squares):1:-1])
22nd Sep 2022, 10:49 PM
ALI Moussa Kadjalla
ALI Moussa Kadjalla - avatar