[Tutor] "if clause" in list comprehensions.

Sander Sweers sander.sweers at gmail.com
Mon Oct 19 19:13:18 CEST 2009

2009/10/19 Eduardo Vieira <eduardo.susan at gmail.com>:
> 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')

> returned this: ['JOHN', 'CANADA', 'RIGHT']
> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT']
> So, actually the "if" acted like a filter.
> In order to use a list comprehension I created this function instead.
> def upperfy(item)
>    try:
>        item = item.upper()
>    except AttributeError:
>        pass
>    return item

I would move return item under the except and remove the pass, other
might disagree on this.

> a = [upperfy(item) for item in mylist]

You can use this which gives the added benefit that you can document
why you are using this within the function. But you can include else
in list comprehension.

a = [item.upper() if hasattr(item, 'upper') else item for item in mylist]

Your case it might be "overkill" to use the function.


More information about the Tutor mailing list