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?

1
  • None is the return value from the calls to print made inside the generator.
    – Tom Karzes
    Commented Mar 27, 2020 at 18:29

2 Answers 2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.