4

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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Anshul Vyas
  • 633
  • 9
  • 19

2 Answers2

7

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)

5

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
C.Nivs
  • 12,353
  • 2
  • 19
  • 44