Unsupported operand types in if/else list comprehension

Mike H cmh.python at gmail.com
Fri Apr 10 17:26:41 EDT 2009


Thanks to all of you.

FYI, I'm doing this because I'm working on creating some insert
statements in SQL, where string values need to be quoted, and integer
values need to be unquoted.

I wanted to be sure that I could pass these values to the list in a
normal way e.g. ['test', 1, 'two'] and have a function correct the
list for me, rather than calling the function with a strangely quoted
list e.g. ['"'test'"', 1, '"'two'"'].

Again, thanks.

On Fri, Apr 10, 2009 at 5:18 PM, John Yeung <gallium.arsenide at gmail.com> wrote:
> On Apr 10, 5:07 pm, Mike H <cmh.pyt... at gmail.com> wrote:
>> 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?
>
> I believe so.  (I'm sure the experts here will tell you more
> definitively.)
>
>> Is there any way I can do this using list comprehension?
>
> Yes.  If you are using 2.5 or later, you can do this:
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a=['test',1,'two']
>>>> b=[(x if not isinstance(x, str) else '"'+x+'"') for x in a]
>>>> b
> ['"test"', 1, '"two"']
>>>>
>
> If you are trying to make a CSV file, then even better may be to use
> the csv module.
>
> John
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list