-1

For example, there is [None, None, None] element when I use list comprehension:

[print(i,v) for i,v in enumerate([1, 2, 3])]
0 1
1 2
2 3
[None, None, None]

But with usual for cycle there is no [None, None, None] element:

for i,v in enumerate([1, 2, 3]):
  print(i,v)
0 1
1 2
2 3

list(enumerate([1, 2, 3]))
[(0, 1), (1, 2), (2, 3)]
dereks
  • 544
  • 1
  • 8
  • 25
  • 3
    `print` doesn't return anything. You usually want to use list comprehensions to hold the output of different functions or expressions. You don't want to use them on things like print that only have side effects – Buckeye14Guy Oct 22 '19 at 15:40
  • What do you mean? – dereks Oct 22 '19 at 15:41
  • 3
    print returns None – Dani Mesejo Oct 22 '19 at 15:41
  • 4
    The list-comprehension is capturing the result of calling `print` - the value or object returned by `print` - which is `None`. As a side-effect of calling `print(i, v)`, the contents of `i` and `v` are displayed, but not captured in the list-comprehension. In addition, this has nothing to do with `enumerate`. – Paul M. Oct 22 '19 at 15:41

1 Answers1

1
[print(x) for x in ...]

This creates a list that is composed of the return value of calling print() over and over.

But print() returns None. Yes, it displays things on the screen, but the actual return value is None.

Therefore your list has a bunch of Nones in it.

John Gordon
  • 29,573
  • 7
  • 33
  • 58