[Tutor] map, filter and lambda functions

alan.gauld@bt.com alan.gauld@bt.com
Thu, 23 Aug 2001 09:58:00 +0100


> Here's the new, shorter version:
> 
> checklist = string.split(filetext, "\n")
> checklist = filter(lambda x: x != '', checklist)
> checklist = map(lambda x: string.strip(x), checklist)
> checklist = map(lambda x: string.upper(x), checklist)

I like it better, to me its clearer whats going on.

> The thing is, I can't use list comprehensions in this script

I'm not convinced comprehensions are better in every case.
They compress a lot of code into one line but not necesarily in
a maintainable form... IMHO of course.

> second version the best (most efficient) way of handling such a code
> block? 

Time them and see... It removes the guesswork!

> Is there a way to do this without lambda functions, or are they
> pretty much needed in this case?

You could define functions:
def isNotEmpty(x): return x != ''
def stripitem(x): return string.strip(x)
def upperitem(x): return string.upper(x)

and use them as in:
checklist = reduce(isNotEmpty, checklist)
checklist = map(stripitem,checklist)
checklist = map(upperitem,checklist)

You can always replace a lambda with a function in Python, 
but in this case the lambda is probably clearer by putting 
the action explicitly in the operation.
The function approach is better if you were using the same 
lambda in multiple places.

Alan G