+ 3
Python List Slice
Hey Can somebody help me please with this question!! What is the output of this code? sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1] The Answer is: [49, 36] But why????? Thanks for your Answers!
10 odpowiedzi
+ 6
-1 = len(array)-1
So you start slicing from the end of the array. The first parameter(7) is included in the slice but the 2nd parameter isn't. So the slice ends at the 6th element.
+ 4
print(sqs[7:5:-1])
7:5=means start from 7 index and end at 4 index 5 will be not included.here you are going 7 to 5 means backward and you need -1 step for backward index.
that's why output is =
7:5:-1=[49,36]
+ 3
var[start:when to stop:how to iterate]
sqs[7:5:-1]
-start in element 7 (49)
-stop if we reach element 5 or pass .
- -1 means we add -1 for iterations.
So :
7
6
stop
See? this results printing 7 element and 6 element (49, 36)
+ 1
Anya LambdaDriver Thanks for your help!!
+ 1
Maninder Singh Thanks!
+ 1
can you help me?
+ 1
what seems to be the problem?
0
Thanks Anya!
so -1 means that the list is read backwards!?
0
Nils yes. It's like LambdaDriver said.
0
No problem Nils