Unsupported operand types in if/else list comprehension

MRAB google at mrabarnett.plus.com
Fri Apr 10 17:23:25 EDT 2009


Mike H wrote:
> Hello all, I have a question about the if/else aspect of list comprehension:
> 
> I would like to go through a list and place quotes around an item if
> it is a string, and keep the item the same if it's anything else:
> 
> e.g.['a',9,'8b'] --> ['"a"', 9, '"8b"']
> 
> I understand that if/else list comprehension should be generally:
> 
> b=[(F,T)[boolean test] for val in X]
> 
> so, I tried the following code:
> 
> a=['test',1,'two']
> b=[(inst, '"'+inst+'"')[isinstance(inst, str)] for inst in a]
> 
> I end up getting the error: unsupported operand type(s) for +: 'int' and 'str'
> 
>>From playing around with other examples, I get the feeling that Python
> is calculating both values (inst and '"'+inst+'"') before selecting
> which one to pass to the new list. Am I right? Is there any way I can
> do this using list comprehension?
> 
Yes, and yes:

     b=[(inst, '"%s"' % inst)[isinstance(inst, str)] for inst in a]



More information about the Python-list mailing list