[Tutor] "if clause" in list comprehensions.
Alan Gauld
alan.gauld at btinternet.com
Tue Oct 20 00:29:40 CEST 2009
Ooops, hit send by mistake...
"vince spicer" <vinces1979 at gmail.com> wrote
>> Lambda can save the day to keep everything on one line, and leave
>> variable
>> type the same:
>>
>> mylist = ['John', 'Canada', 25, 32, 'right']
>> new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a
>> in
>> mylist ]
>>
>> >> ['JACK', 'CANADA', 25, 32, 'RIGHT']
In what way does lambda help?
new_list = [y.upper() if hasattr(y, 'upper') else y for y in mylist]
does exactly the same and is shorter.
lambda helps if you want to pass a function object around but
defining it and immediately calling it means it can be replaced
directly by the expression within the lambda.
But using hasattr() still has the problem of failing if upper is not a
callable attribute (or does something radical like exiting)
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list