Ooops, hit send by mistake...
"vince spicer" <vinces1...@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/
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor