Unsupported operand types in if/else list comprehension

Gary Herron gherron at islandtraining.com
Fri Apr 10 17:18:40 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?
>
> Thanks in advance,
>
> Michael
> --
> http://mail.python.org/mailman/listinfo/python-list
>   
While I think your goal is of questionable value, this will do it:

    b = [('"'+inst+'"' if isinstance(inst, str) else inst)   for inst in a]

The parentheses around the conditional are unnecessary, but help with 
readability I think.

Better yet:
  def  QuoteIfString(inst):
      ...

  b = [QuoteIfString(inst)   for inst in a]

would be much more readable, and you could document
*why* you are doing this in the def of QuoteIfString


Gary Herron










More information about the Python-list mailing list