[Tutor] map, filter and lambda functions

Steven Burr sburr@mac.com
Thu, 23 Aug 2001 22:40:47 -0700


On Thursday, August 23, 2001, at 01:58 AM, alan.gauld@bt.com wrote:

>> 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.

You're surely right that list comprehensions aren't better in every 
case.  In this case, though, it's really too bad (or at least it seems 
so to me) that Sheila doesn't have access to them:

 >>> filetext = """lower case string
... with trailing white space and
...
... a blank line                """
 >>> checklist = [s.strip().upper() for s in filetext.split('\n') if s]
 >>> checklist
['LOWER CASE STRING', 'WITH TRAILING WHITE SPACE AND', 'A BLANK LINE']