> I have to confess that I already use map(), or should I say abuse, for > this, although it is the first time I consider using lambdas. Up until > now I always used map() to perform a looped call on a function that > would change the attribute value, as shown in Mark Lutz & David Ascher's > Learning Python: > > # Perform attribute value change on a single instance > def iterateInstances( oInstance ): > oInstance.value = myValue > > # Loop over list of instances > map( iterateInstances, aListOfInstances )
What!!! Seriously? I'm making a style judgement here, so perhaps I could be wrong, but I think that's terrible that Learning Python has such an example. If you have a page number, I'll look it up and then write a complaint. *grin* The major problem here is that both map() and list comprehensions are really meant to be used because they generate a list of return values. If we use a map() or list comprehensions, such as: map(lambda x: x^2, [1, 2, 3]) [x^2 for x in [1, 2, 3]] then we're really saying something like this: [1, 2, 3] | | | | | | map() | | | V V V [1, 4, 9] where map() produces a list of values. If we're using map() just because it evaluates something on every element on a list, then, to make the intent more clear, we really should either use something like a foreach() function instead of map(): ###### def foreach(function, l): """Apply some function on every element in l. Does not accumulate return values.""" for x in l: function(l) ###### If we use something like foreach(0, then this makes it clear that we really don't care about return values at all. I should add that I'm arguing for style here. Things do work pefectly well with map() too --- the computer doesn't care that it's throwing return values away --- but we should do our best to document intent in our programs. Best of wishes! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor