Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
map function
#1
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
Reply
#2
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?
Reply
#3
(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?
Reply
#4
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.
Reply
#5
(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.
Reply
#6
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020