[Tutor] "if clause" in list comprehensions.
eduardo.susan at gmail.com
Mon Oct 19 23:58:27 CEST 2009
On Mon, Oct 19, 2009 at 1:20 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Sander Sweers" <sander.sweers at gmail.com> wrote
>>> mylist = ['John', 'Canada', 25, 32, 'right']
>>> a = [item.upper() for item in mylist if type(item) == type('good')]
>> Usually it is recommended to use hasattr() instead of type()
>> hasattr(s, 'upper')
> Nope, they do completely different things
> I think you might be thinking of isinstance() which can be used instead of
> type(). I see you use hasattr as a means of testing for a method but that is
> still different from testing type - the method names might be the same but
> the functions be completely different in effect!
>>> returned this: ['JOHN', 'CANADA', 'RIGHT']
>>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT']
>>> So, actually the "if" acted like a filter.
> It is intended to be used as a filter.
>>> In order to use a list comprehension I created this function instead.
>>> def upperfy(item)
>>> item = item.upper()
>>> except AttributeError:
>>> return item
>> I would move return item under the except and remove the pass, other
>> might disagree on this.
> I would :-)
> Doing that would result in None being returned for each successful
> conversion. The OPs code is correct (even if unnecessary)
>>> a = [upperfy(item) for item in mylist]
> a = [item.upper() if type(item) == str else item for item in mylist]
> should do it I think.
> Alan Gauld
> Author of the Learn to Program web site
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Thanks for all the guidance. I'm glad I learned I could use "else" in
the list comp. after all. I thought I could, but when I tried it, I
got it wrong and forgot how I did it. Yeah, I had an impression that a
function was unnecessary in this case, but didn't know how to get
To: Emmanuel: Thanks for your remark in the case of unicode. In my
code that wasn't a problem, but it's something to consider.
More information about the Tutor