+ 1

Why output of this code is 9? Plz explain line 2 & 3.

x = [ i for i in range(10)] r = slice( 3, None) print(x[r] [r] [r])

24th Feb 2020, 12:08 PM
Peter Parker
Peter Parker - avatar
2 Answers
+ 5
Line 2 is equivalent to writing x[3:]. So it gets all the elements from index 3 to the end. If you apply the same pattern again on the resulting list, you jump 3 steps further forward, the resulting list will be smaller. And then once again. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][3:] ->[3, 4, 5, 6, 7, 8, 9][3:] ->[6, 7, 8, 9][3:] ->[9]
24th Feb 2020, 12:26 PM
HonFu
HonFu - avatar
+ 5
x[slice(3, None)] equals: x[3:] You were trying to make a slice: x[3:][3:][3:] And you need to take slice after slice. x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] x[3:][3:][3:] -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][3:][3:][3:] -> [3, 4, 5, 6, 7, 8, 9][3:][3:] -> [6, 7, 8, 9][3:] -> [9]
24th Feb 2020, 12:28 PM
Seb TheS
Seb TheS - avatar