Issue
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?
[Edit:] Related posts: "Why does the print function return None" (but no loops or list actions there), and "Is it pythonic to use list comprehensions just for side effect?" (but more abstract, no print function there)
Solution
[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
Answered By - FlyingTeller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.