Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Generator expressions work internally in python? [duplicate]

I have tried this following code:

result = (x for x in range(3))


for y in result:
    print(y)

I am getting the following Output:

0
1
2

But when I am using this code :

result = (print(x) for x in range(3))


for y in result:
    print(y)

I am getting the following output:

0
None
1
None
2
None
    

Can anyone explain, Why this None is coming in output in second code?

like image 789
Anshul Vyas Avatar asked Sep 12 '25 22:09

Anshul Vyas


2 Answers

Because print(x) prints the value of x (which is the digits that get printed) and also returns None (which is the Nones that get printed)

like image 162
DisappointedByUnaccountableMod Avatar answered Sep 14 '25 12:09

DisappointedByUnaccountableMod


print doesn't return a value, so you are seeing None, which is the return for print, and the output from print. This is a classic case of using comprehension syntax for side effects, which is not using the generator/comprehension syntax to contain an actual result. You can check this by running:

print(print('x'))
x
None
like image 20
C.Nivs Avatar answered Sep 14 '25 11:09

C.Nivs