简体   繁体   中英

Why list comprehension with map() function in python can return None

>>> counters = [1,2,3,4]
>>> 
>>> [print(i, end=', ') for i in map(inc, counters)]

4, 5, 6, 7, [None, None, None, None]

Why does this code print [None, None, None, None] ?

Because print returns None ?

So, the print is done ( 4, 5, 6, 7, ) and then the list comprehension is returned ( [None, None, None, None] )

What you want to do is use join:

>>> ', '.join(str(i) for i in map(inc, counters))
'4, 5, 6, 7'

or use the sep argument of print (I don't have python3 right now but something like this:)

print(*map(inc, counters), sep=', ')

print is a function but it return None that's why you are getting none

Do this

In [3]: [i for i in map(abs, counters)]
Out[3]: [1, 2, 3, 4]

In [7]: a = print(1234)
1234

In [11]: print(a)
None

[print(i, end=', ') for i in map(inc, counters)]

so when you do this print prints i 1, 2, 3, 4, and then each time list comprehension return the output which is None hence None, None, None, None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM