I was working with Python, and I noticed that the map()
function doesn't really seem to do much. For instance, if I write the program:
mylist = [1, 2, 3, 4, 5]
function = map(print, l)
print(function)
It provides no advantages over:
mylist = [1, 2, 3, 4, 5]
for item in mylist:
print(item)
In fact, the second option creates fewer variables and seems generally cleaner overall to me. I would assume that map()
provides advantages that cannot be seen in an example as simplistic as this one, but what exactly are they?
EDIT: It seems that some people have been answering a different question than the one I intended to ask. The developers who made Python obviously put some work into creating the map()
function, and they even decided NOT to take it out of 3.0, and instead continue working on it. What essential function did they decide it served?
map
is C code so it's fasterfunction = map(print, l); print(function)
is not how you would usemap
to print the elements of a list, even if usingmap
for that were a good idea. You'd uselist(map(print, l))
, to exhaust themap
iterator, rather than printing the iterator itself.map()
and just want to consume the iterator, you'd have to use something likeconsume = lambda iterator: deque(iterator, maxlen=0)
.map
is not intended to be used for side effects, and people expect it not to have any.consume(map(print, l))
is fairly straightforward, not terribly bug-prone, and not potentially memory-intensive, but it generally doesn't offer any benefit overfor x in l: print(x)
. More complex expressions in themap
call grow unreadable, and whoever has to maintain your code probably won't like it.