Python Forum
map function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: map function (/thread-1807.html)



map function - landlord1984 - Jan-26-2017

map(print,[1,2,3])
I thought above code should print individual element, but it does not work.

Why map function does not work here?

L


RE: map function - micseydel - Jan-26-2017

Could you elaborate on "it does not work"? Do you get an error? If no error, presumably the values aren't printed, but does something else happen instead?


RE: map function - landlord1984 - Jan-27-2017

(Jan-26-2017, 11:55 PM)micseydel Wrote: map(print,[1,2,3])
Output is <map at 0x1099dc160>

I know the map function returns a generator, but shouldn't it execute the function print?


RE: map function - micseydel - Jan-27-2017

Ok, it sounds like you're using Python 3.

Generators are lazy, so until you do something with them they represent more potential than work done. map() and comprehensions (syntactic sugar for maps) are ideal for cases where you're generating iterables of values to be used by something else, if you want side effects (e.g. printing, network stuff, reading / writing files) you should probably use an explicit for loop.


RE: map function - landlord1984 - Jan-27-2017

(Jan-27-2017, 12:39 AM)micseydel Wrote: Ok, it sounds like you're using Python 3. Generators are lazy, so until you do something with them they represent more potential than work done. map() and comprehensions (syntactic sugar for maps) are ideal for cases where you're generating iterables of values to be used by something else, if you want side effects (e.g. printing, network stuff, reading / writing files) you should probably use an explicit for loop.

Ok. I see. I know how to this by loop. I am just interested to test other alternative ways e.g. by map.


RE: map function - micseydel - Jan-27-2017

In Python, using a map for it isn't very appropriate. map() is good for mapping from some values to some other values. print() returns None, so you're not really mapping to anything.

Another way to look at it is that map() is a functional idea, and in functional programming side-effects are evil.

If you simply call list() on the generator returned by map(), you'll get the output. But as you can tell by the code, it's just not ideal. Your code makes it look like you want a list, when you don't, and creating that list means you'll be using memory that you don't need to occupy.