Does map() iterate through the list like “for” would? Is there a value in using map vs for?
If so, right now my code looks like this:
for item in items:
item.my_func()
If it makes sense, I would like to make it map(). Is that possible? What is an example like?
You could use
mapinstead of theforloop you’ve shown, but since you do not appear to use the result ofitem.my_func(), this is not recommended.mapshould be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop.Also, as of Python 3.0
mapreturns an iterator, so in that casemapwill not behave the same (unless you explicitly evaluate all elements returned by the iterator, e.g. by callingliston it).Edit: kibibu asks in the comments for a clarification on why
map‘s first argument should not be a function with side effects. I’ll give answering that question a shot:mapis meant to be passed a functionfin the mathematical sense. Under such circumstances it does not matter in which orderfis applied to the elements of the second argument (as long as they are returned in their original order, of course). More importantly, under those circumstancesmap(g, map(f, l))is semantically equivalent tomap(lambda x: g(f(x)), l), regardless of the order in whichfandgare applied to their respective inputs.E.g., it doesn’t matter whether
mapreturns an iterator or a full list at once. However, iffand/orgcause side effects, then this equivalence is only guaranteed if the semantics ofmap(g, map(f, l))are such that at any stagegis applied to the first n elements returned bymap(f, l)beforemap(f, l)appliesfto the *(n + 1)*st element ofl. (Meaning thatmapmust perform the laziest possible iteration—which it does in Python 3, but not in Python 2!)Going one step further: even if we assume the Python 3 implementation of
map, the semantic equivalence may easily break down if the output ofmap(f, l)is e.g. passed throughitertools.teebefore being supplied to the outermapcall.The above discussion may seem of a theoretic nature, but as programs become more complex, they become more difficult to reason about and therefore harder to debug. Ensuring that some things are invariant alleviates that problem somewhat, and may in fact prevent a whole class of bugs.
Lastly,
mapreminds many people of its truly functional counterpart in various (purely) functional languages. Passing it a "function" with side effects will confuse those people. Therefore, seeing as the alternative (i.e., using an explicit loop) is not harder to implement than a call tomap, it is highly recommended that one restricts use ofmapto those cases in which the function to be applied does not cause side effects.