Albert-Jan Roskam wrote:
Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x?
Or did I miss something?
Cheers!!
Albert-Jan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before you criticize someone, walk a mile in their shoes, that way
when you do criticize them, you're a mile away and you have their shoes!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--- On Tue, 10/20/09, Alan Gauld <alan.ga...@btinternet.com> wrote:
From: Alan Gauld <alan.ga...@btinternet.com>
Subject: Re: [Tutor] "if clause" in list comprehensions.
To: tutor@python.org
Date: Tuesday, October 20, 2009, 12:29 AM
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
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
Python 2.5+ if memory serves me correctly. I know 2.4 running on one of
our servers does not support the else section.
--
Kind Regards,
Christian Witts
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor