-1

I'm trying to understand List-comprehensions in python , I came across this behaviour of list comprehension. when I do: [print(y) for y in range(0,10)] it gives response

0
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None, None]

I understand it prints 0 to 9, but I don't understand why it prints None .But when I do o = [print(y) for y in range(0,10)] it prints

0 1 2 3 4 5 6 7 8 9

This time without any none,I couldn't find any relevant stuff by searching, can someone please explain , Thanks

Shubham Devgan
  • 609
  • 6
  • 18

4 Answers4

3

If you type anything from the interpreter, it will echo whatever the function or expression returns, unless it is None (the default).

For example:

>>> 1+1
2

Similarly, the print function calls get executed while the expression is being built, but the list of Nones is actually the result of the expression.

You probably want to do something with it, so either:

[y for y in range(0,10)]

Or:

mylist = [y for y in range(0,10)]

Makes more sense. The print function prints the value, but then returns None and the value it printed is lost.

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • 2
    To nitpick, in Python 3 `print` is no longer a statement but a function, which is what is used here. – Jan Christoph Terasa Jan 09 '20 at 07:48
  • In fact the `print` function call is still a statement. You're right though that `print` by itself is no longer a valid statement and needs to be called as a function, but you could tell I was aware due to what I'm saying on the final line. I don't think there's anything wrong or confusing about what I was saying. – Grismar Jan 09 '20 at 07:53
  • True, any expression (including function call) is a statement, so my wording is not really correct. But not every statement will have a return value, but functions have. That is the main gist here, and why I think it is worthwhile to point out that `print` is a *function* and not only a statement. As I said, just a nitpick, the answer is fine. – Jan Christoph Terasa Jan 09 '20 at 07:59
2

The print function returns None, and you put these Nones into your list. The elements are what the function returns, not what is printed on the screen. The printing-on-the-screen part is a side-effect of the print function.

Since there are already plenty of other answers showing what you probably wanted to do, I will not reproduce them here.

Jan Christoph Terasa
  • 5,781
  • 24
  • 34
1

Because you are basically doing thing like this:

x = []
for y in range(0,10):
    x.append(print(y))

print(x)

You should try [y for y in range(10)] instead.

wong.lok.yin
  • 849
  • 1
  • 5
  • 10
1

It is because print function prints output to the console, not to the list. This will give you your result:

[y for y in range(0,10)]

Or

list(map(lambda y: y, range(0,10)))
Wasif
  • 14,755
  • 3
  • 14
  • 34