+ 1

Why it prints [1 , 25 ,81]?

x = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(x[1::4]) This code is supposed to plus 4 from 1 up to the end and among all the matches it has with other numbers like 9 "1+4+4=9" it only prints [1, 25, 81]. Why? Btw 25 and 81 are also the result of 1+4...... but why the computer prints them? Any answer will be appreciated.

10th Nov 2022, 5:35 PM
Engineer X
Engineer X - avatar
5 Answers
+ 9
x[1::4] means a slice that starts at index 1 (that's number 1 in the list), goes to the end of the list (because second value between the two colons is not specified) and it takes every 4th value only (that's the third argument). So 3 numbers are skipped between 1 and 25, and between 25 and 81.
10th Nov 2022, 5:54 PM
Tibor Santa
Tibor Santa - avatar
+ 4
Thanks Tibor Santa , So it takes the 4th value. Now I get it.
10th Nov 2022, 7:39 PM
Engineer X
Engineer X - avatar
+ 3
Thanks Oma Falk for the message , Yeah good code you have written there, but I was just a little confused about how the code works. I wasn't looking for a new code but again thank you.
10th Nov 2022, 7:40 PM
Engineer X
Engineer X - avatar
+ 2
Try print([i for i in x if i % 4 ==1])
10th Nov 2022, 6:51 PM
Oma Falk
Oma Falk - avatar
+ 1
It takes the 4th value
11th Nov 2022, 10:34 PM
Michael Berhane
Michael Berhane - avatar