[Tutor] "if clause" in list comprehensions.
Eduardo Vieira
eduardo.susan at gmail.com
Mon Oct 19 18:39:51 CEST 2009
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']
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.
Eduardo
More information about the Tutor
mailing list