Search code examples
pythonexpressiongenerator

How Generator expressions work internally in python?


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?


Solution

  • 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)