On Mon, Oct 19, 2009 at 11:39 AM, Eduardo Vieira <eduardo.su...@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. HTH, Wayne
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor