0

Simple question about print function (python 3.9.13) what causes these (a link to some informative page will be appreciated). I have a list of strings and I want to print them each on separate line in an interactive session.

>>> aa = ['word 1','test 2', 'blah 3', 'ding 4']
>>> [print(x) for x in aa]
word 1
test 2
blah 3
ding 4
[None, None, None, None]
>>> (print(x) for x in aa)
<generator object <genexpr> at 0x000001D8AC975DD0>
>>> print(x) for x in aa
SyntaxError: invalid syntax
>>> {print(x) for x in aa}
word 1
test 2
blah 3
ding 4
{None}
>>> 

Question: could you explain these behaviours, especially what causes those None to appear and how to avoid it?

Mark
  • 7,785
  • 2
  • 14
  • 34
user9393931
  • 177
  • 2
  • 9

2 Answers2

3

None appears in these areas because print returns None (I could try to explain this, but others on StackOverflow have explained this better, such as this answer.

>>> [print(x) for x in aa]

Because the output of print("foo") is None, the output of [print(x) for x in aa] is going to be [None, None, None None], (one None for each element of aa.

>>> (print(x) for x in aa)

This creates a generator object, something which can later be iterated over:

o = (print(x) for x in aa)

for i in o:
    i

# output is 
1
2
3
4
5 

>>> {print(x) for x in aa}

This is similar to example #1, except instead of creating a list, it creates a set (basically an unordered list with only unique values). Since there is only one unique value in the list [None, None, None None], the whole thing is reduced down to {None}

How to avoid it

The simplest way of avoiding it is to use print outside of things similar to list comprehensions. Instead of [print(x) for x in aa], do print([x for x in aa]). Also, if you create functions, have them return values, then call the function with print, instead of having the function end by printing a value.

Mark
  • 7,785
  • 2
  • 14
  • 34
2

[print(x) for x in aa], {print(x) for x in aa} are list and dictionary comprehensions. (print(x) for x in aa) is a generator comprehension. The syntax can be read as:

For each element x in the iterable aa, emplace the return value of (print(x) into a list/set. So for each element x, print(x) is executed, prints the result and returns None. You are seeing that print resulted in each element being printed, but also see the resulting list, that only contains None.

See https://docs.python.org/3.9/whatsnew/2.0.html?highlight=comprehension#list-comprehensions for list comprehensions

What you can do is to write

for x in aa: print(x)

on a single line and then hit enter twice

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53