map

Piet van Oostrum piet at cs.uu.nl
Mon Aug 31 05:31:34 EDT 2009


>>>>> Hendrik van Rooyen <hendrik at microcorp.co.za> (HvR) wrote:

>HvR> On Monday 31 August 2009 06:55:52 elsa wrote:
>HvR> 8< --------- map question ----------------------------

>>> 
>>> (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList
>>> [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want
>>> to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc
>>> (myList[2], 'woo') some other time).

>HvR> Here is some heretical advice:

>HvR> Do not use stuff like map and reduce unless they fit what you want to do 
>HvR> perfectly, and "JustWorks" the first time.

>HvR> You have a very clear idea of what you want to do, so why do you not just 
>HvR> simply write something to do it?

>HvR> something like this (untested):

>HvR> def woofer(thefunc,thelist,thething):
>HvR> 	theanswers = []
>HvR> 	for x in thelist:
>HvR> 		theanswers.append(thefunc(x,thething))
>HvR> 	return theanswers

>HvR> And the advantage is that you do not have to remember what map does...

Map should be in every good programmer's toolbox. So (s)he presumably
knows already what map does. In order to follow your advise (s)he must
first forget what map does :=)

Agreed on the part that map shouldn't be used indiscriminately. Neither
should loops. Your woofer is much harder to follow than map, I think.

[myFunc(elt, 'booHoo') for elt in myList] is also a good candidate and
in this case I think it is preferable to both the loop and the map with
a partial or lambda in terms of clarity.

On the other hand when you just want to call a function on each element
of a list and you don't need to collect the result a simple loop is
often preferable.

But ultimately it is also very much a matter of taste, preference and habit.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list