[Tutor] "if clause" in list comprehensions.

Wayne srilyk at gmail.com
Mon Oct 19 19:25:55 CEST 2009

On Mon, Oct 19, 2009 at 11:39 AM, Eduardo Vieira <eduardo.susan at gmail.com>wrote:

> Hello,
> The other day I was making a script and decided to use a list
> compreehension and I found out that this code:
> mylist = ['John', 'Canada', 25, 32, 'right']
> a = [item.upper() for item in mylist if type(item) == type('good')]
> returned this: ['JOHN', 'CANADA', 'RIGHT']
> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT']

What type is 'good' ? What type is 25? Also, perhaps you misunderstand what
a list comprehension does:

a = [item for item in mylist if type(item) == type('good')]

will look at the first item - is it of type string? if so then it's added to
the list, otherwise it's ignored.

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
> a = [upperfy(item) for item in mylist]
> My question is? Am I solving the problem in the right way? Am I
> missing something?
> Thanks for all the help I've been getting as a newcomer.

I don't know if it's the "right" way, but it looks fine to me.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091019/781ecbe7/attachment.htm>

More information about the Tutor mailing list