Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 521
matiit Avatar asked Oct 11 '11 19:10

matiit


People also ask

Why is my print function not working?

Do a hard reset on your printer. To do this you just need to turn off your printer, unplug for a few minutes and then plug the printer again. If that still doesn't work, try turning the printer and your computer off, and then start it back up again. Try uninstalling and then reinstalling your printer driver.

How do you show an object on a map in Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.

What is map () in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


1 Answers

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.

like image 193
cwallenpoole Avatar answered Oct 21 '22 21:10

cwallenpoole