Print doesn't print when it's in map, Python

Python 3.xDictionary

Python 3.x Problem Overview


primes = [2,3,5,7..] (prime numbers)
map(lambda x:print(x),primes)

It does not print anything. Why is that? I've tried

sys.stdout.write(x)

too, but doesn't work either.

Python 3.x Solutions


Solution 1 - Python 3.x

Since lambda x: print(x) is a syntax error in Python < 3, I'm assuming Python 3. That means map returns a generator, meaning to get map to actually call the function on every element of a list, you need to iterate through the resultant generator.

Fortunately, this can be done easily:

list(map(lambda x:print(x),primes))

Oh, and you can get rid of the lambda too, if you like:

list(map(print,primes))

But, at that point you are better off with letting print handle it:

print(*primes, sep='\n')

NOTE: I said earlier that '\n'.join would be a good idea. That is only true for a list of str's.

Solution 2 - Python 3.x

This works for me:

>>> from __future__ import print_function
>>> map(lambda x: print(x), primes)
2
3
5
7
17: [None, None, None, None]

Are you using Python 2.x where print is a statement, not a function?

Solution 3 - Python 3.x

Alternatively, you can unpack it by putting * before map(...) like the following

[*map(...)]

or

{*map(...)}

Choose the output you desire, a list or a dictionary.

Solution 4 - Python 3.x

Another reason why you could be seeing this is that you're not evaluating the results of the map function. It returns a generator (an iterable) that evaluates your function lazily and not an actual list.

primes = [2,3,5,7]
map(print, primes) # no output, because it returns a generator
primes = [2,3,5,7]
for i in map(print, primes):
    pass # prints 2,3,5,7

Alternately, you can do list(map(print, primes)) which will also force the generator to be evaluated and call the print function on each member of your list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmatiitView Question on Stackoverflow
Solution 1 - Python 3.xcwallenpooleView Answer on Stackoverflow
Solution 2 - Python 3.xJohn Gaines Jr.View Answer on Stackoverflow
Solution 3 - Python 3.xAnastasiya-Romanova 秀View Answer on Stackoverflow
Solution 4 - Python 3.xAnirudh RamanathanView Answer on Stackoverflow