0
sqs=[0,1,4,9,16,25,36,49,64,81]
print (sqs [7:5:-1]) here. 7 is the start index. 5 is the ending index. the minus sign(-) means we should start from the end of the list. my question is what does 1 (the number after minus sign) indicates. and what is the output. and how???? explain me in details plis. thank you
7 Answers
+ 7
The 1 after the (-) tells the steps taken backwards.
+ 6
You can slice or create a substring starting from right to left (inverse order) or left to right. In your example the list has 10 elements from 0 to 10, you are saying slice or create a substring in an inverse order from position 7(49) back to position 5(25, not including position 5 python works like this), going back 1 position at the time (-1).
So you need the - because you are using inverse order 7:5, if you were using 5:7 you could scape the :1 at the end.
+ 2
1 is step
[7:5:-1] slice gives: [49,36] - values with indexes [7], [6].
last index [5] of list slice is not included
slice [8:5:-2] gives: [64,36]
+ 2
-1 makes you start at the end and counting 1 back each time so 81,64,49,36... you can reverse the whole list with sqs[::-1]
+ 1
i dont know your answer
0
whats output???
- 1
sqs = [i**2 for i in range(10)]
sqs[7:5:-1]
The third parameter in the slice is the step parameter, basically: how much you travel each time