Unsupported operand types in if/else list comprehension

Terry Reedy tjreedy at udel.edu
Fri Apr 10 20:37:37 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?

I would just use an old-fashioned for loop, especially if it were ok to 
quote the strings 'in-place'.

for i, item in enumerate(X):
   if isinstance(item,str):
     X[i] = '"'+item+'"'

tjr




More information about the Python-list mailing list