+ 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!

5th Nov 2018, 3:17 PM
Nils
Nils - avatar
10 Respostas
+ 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.
5th Nov 2018, 3:39 PM
Lambda_Driver
Lambda_Driver - avatar
+ 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]
5th Nov 2018, 4:07 PM
Maninder $ingh
Maninder $ingh - avatar
+ 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)
5th Nov 2018, 3:37 PM
Anya
Anya - avatar
+ 1
Anya LambdaDriver Thanks for your help!!
5th Nov 2018, 3:44 PM
Nils
Nils - avatar
+ 1
5th Nov 2018, 4:08 PM
Nils
Nils - avatar
+ 1
can you help me?
10th Nov 2018, 1:36 PM
Dinda Ayu
Dinda Ayu - avatar
+ 1
what seems to be the problem?
10th Nov 2018, 2:55 PM
Lambda_Driver
Lambda_Driver - avatar
0
Thanks Anya! so -1 means that the list is read backwards!?
5th Nov 2018, 3:41 PM
Nils
Nils - avatar
0
Nils yes. It's like LambdaDriver said.
5th Nov 2018, 3:43 PM
Anya
Anya - avatar
0
No problem Nils
5th Nov 2018, 3:45 PM
Lambda_Driver
Lambda_Driver - avatar