+ 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?
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.
+ 5
Ruslan Guliyev defaults:
going forward the first value is most left,
Going backwards the first value is most right
It is straightforward.
+ 4
No!
print(squares[:1:-1]) identical to this:
print(squares[len(squares):1:-1])
+ 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.
+ 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?
+ 2
#index: 0, 1, 2, 3...
values = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#index:-10,-9,-8,-7...
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])