Can Anyone explain the output of these step by step ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can Anyone explain the output of these step by step ?

sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1])

11th Jan 2020, 11:52 AM
ayushman tiwari
ayushman tiwari - avatar
4 Answers
+ 9
The 1 after the (-) tells the steps taken backwards. sqs[start:stop:step] so step is negate so it will traverse list in backward direction. sqs[7:5:-1] This is similar to range but here start is 7, stop is 5 and step size is -1. Hence it generates a descending order list. Now the values it generates are : [7, 6] 5 is not counted because, stop =5 and we have to consider only upto stop-1, i.e 5-(-1) = 6. This is how it works. Now at 7 index 49 and 6 index 36 is printed [49 36] Slice step could be both positive and negative. So you can walk throught the list forward or backward. That is why you have >>> sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> print(sqs[7:5:-1]) [49, 36]
11th Jan 2020, 12:12 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 8
Here is some more slicing concept which can help you in all ways. https://www.sololearn.com/Discuss/2130822/?ref=app
11th Jan 2020, 12:14 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 4
sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(sqs[7:5:-1]) # result is: [49, 36] sqs[7:5:-1]) is a slice with list sqs. List sqs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] values 0 1 2 3 4 5 6 7 8 9 index -1 means, that the iteration starts at the end of the list and going backwards. It starts at index 7 and ends at index 5, but not including 5. So it's just index 7 (49) and index 6 (36).
11th Jan 2020, 1:45 PM
Lothar
Lothar - avatar
+ 1
It prints a list starting from the 7th index of sqs, up till the 5th index. It goes in the backwards direction because the steps specified is -1.
11th Jan 2020, 12:00 PM
XXX
XXX - avatar