Can you explain me this code make in phyton? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can you explain me this code make in phyton?

y=[x for x in range (10) if x // 3 == 2] print( sum(y)). I know that the answer is 21 but I dont understand why. I dont understand the syntax. I know that this code is the same that y=0 for x in range (10): if x//3==2: y=y+x print(y)

27th Mar 2019, 1:22 AM
Juan Pablo Herran
Juan Pablo Herran - avatar
6 Answers
+ 2
It's a list comprehension sir... You better glance once that concept
27th Mar 2019, 1:39 AM
Mallikarjunagoud A
Mallikarjunagoud A - avatar
+ 1
It's a list comprehension, it's given in the solo learn course. We can use lists operation with conditions inside "[ ]" So when we do : y = [ x for x in range(10) if x//3 == 2] Y becomes a list And y is : [6, 7, 8] **See the course again**
27th Mar 2019, 1:40 AM
RZK 022
RZK 022 - avatar
0
x//3 : is floor division, hope you know what that means So when we run the loop only 3 numbers qualify the condition 6, 7 and 8 : as 6//3 = 2, 7//3 = 2 and 8//3 = 2, it's just division but just ignore whatever you have in the points, doesn't matter, So the sun is : 6+7+8 = 21
27th Mar 2019, 1:31 AM
RZK 022
RZK 022 - avatar
0
That I understand, I think that your answer is for only the loop for. But the part y=[x..... I dont understand. Why is it building a list? Please sorry my English.
27th Mar 2019, 1:37 AM
Juan Pablo Herran
Juan Pablo Herran - avatar
0
Thanks Diego. I have not reached that concept in the course, in the first module of list do not mention this concept
27th Mar 2019, 2:29 AM
Juan Pablo Herran
Juan Pablo Herran - avatar