0

I have mistakenly printed the shortcode in python jupyter notebook as below:

[print(i) for i in range(0,3)]
Output>
0
1
2
[None, None, None, None, None, None, None, None, None, None]

I can not understand why it is a printing list of None at the last? Kindly explain to me about this.

  • 2
    `[None, None, None, None, None, None, None, None, None, None]` is the result of the list comprehension you have created.. `print(i)` is a function that returns `None` – Nikos M. May 25 '20 at 17:04
  • 1
    Does this answer your question? [Python Script returns unintended "None" after execution of a function](https://stackoverflow.com/questions/16974901/python-script-returns-unintended-none-after-execution-of-a-function) – DYZ May 25 '20 at 17:23

2 Answers2

2

You ran

[print(i) for i in range(0, 10)]

which captured the None return value from print, ten times.

To avoid this, consider running it without a list comprehension:

for i in range(10):
    print(i)
J_H
  • 17,926
  • 4
  • 24
  • 44
0

Python REPL where you run the code, outputs the evaluated result of the code you gave it.

So:

if I give it a list comprehension like:

[i for i in range(0,3)]

even though I wont explicitly print it the python REPL will print the evaluated result as

[0,1,2]

Now you get confused because you use print(i) function with a list comprehension.

So print(i) prints the i but also its return value (which is None) is used to create the list through list comprehension:

[print(i) for i in range(0,3)]

so the output is the output of the print(i) PLUS the REPL output of the evaluated list which is a list of None's

0
1
2
[None, None, None]

In other words you created a list of None's but along the way you also printed some values. if you only want to loop over some values and print then (and NOT create a list) then do:

for i in range(0, 3): print(i)
Nikos M.
  • 8,033
  • 4
  • 36
  • 43