[Tutor] "if clause" in list comprehensions.
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:
> 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)
> item = item.upper()
> except AttributeError:
> 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...
More information about the Tutor