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?
Because print(x)
prints the value of x (which is the digits that get printed) and also returns None
(which is the None
s that get printed)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With