0

on running

[print(n) for n in range(5)]

it gives

0
1
2
3
4
[None, None, None, None, None]
pault
  • 41,343
  • 15
  • 107
  • 149
apostofes
  • 2,959
  • 5
  • 16
  • 31
  • 2
    `print` returns `None`. The result of the list comprehension is the sequence of values returned by your function. – IronMan Aug 07 '19 at 21:12
  • Also: [List comprehension returning values plus [None, None, None\], why?](https://stackoverflow.com/questions/18193205/list-comprehension-returning-values-plus-none-none-none-why) – pault Aug 07 '19 at 21:13
  • Also: https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects – juanpa.arrivillaga Aug 07 '19 at 21:18
  • 1
    ok, I got it, it is like print([print(0), print(1), print(2), print(3), print(4)]) – apostofes Aug 07 '19 at 21:21
  • Please don't use a list comp unless you actually want a list. See [Is it Pythonic to use list comprehensions for just side effects?](https://stackoverflow.com/q/5753597/4014959) – PM 2Ring Aug 13 '22 at 01:21

4 Answers4

3

The list comprehension effectively does this:

L = []
for n in range(5):
    r = print(n)
    L.append(r)
print(L)

print(...) has the side-effect of displaying the arguments to screen, but has a return value of None. This is why a list of Nones is created. However, when you run this in the shell, you're asking to see the list-comp'd list... which is five Nones

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

print() doesn't return anything. So, when you call [print(n) for n in range(5)], it's printing n 5 times as it creates an array of 5 Nones.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
2

print(n) returns None so the resulting list from the list comprehension will be [None]*5

Wamadahama
  • 1,489
  • 13
  • 19
2

print doesn't return its argument; it writes it to the file handle used for standard output and returns None. The expected list is produced by [n for n in range(5)].

Interactive interpreters confuse the issue a bit because they always print the value of an expression to standard output after evaluating it. In your example, standard output gets 0 through 4 written by the evaluation of the calls to print, then the interpreter itself prints the string representation of the resulting list to standard output as well. If you put the same code in a file and run it outside an interactive interpreter, you'll see only the first 5 lines, but not the resulting list.

chepner
  • 497,756
  • 71
  • 530
  • 681