Where's the List?

Stephen Hansen apt.shansen at gmail.com
Sat Jun 5 16:52:15 EDT 2010


On Sat, Jun 5, 2010 at 1:17 PM, Victor Subervi <victorsubervi at gmail.com>wrote:

>           option_values = []
>

Here you create a list. You also can get option_values by slicing your
'order' variable, and I assume that is actually producing a tuple.
Otherwise, you wouldn't get the error you're getting. Either way, you go on
to do some strangeness:

        cursor.execute(sql, tuple([pkg, prodid, tmpTable, quantity] +
> option_values))
>

I'm not at all sure why you're building a list, adding option_values to it,
then trying to convert it all into a tuple. That's sorta a lot of wasted
conversion going on. Splitting that single line up into multiple lines to
clarify exactly what is going on:

    foo1 = [pkg, prodid, tmpTable, quantity]
    foo2 = foo1 + option_values
    foo3 = tuple(my_list)

    cur.execute(sql, foo3)

Although its all on one line, those three separate actions are done in that
order when said line is executed. The problem is on foo2.

During the execution of foo2, my_list -- a list, not a tuple -- is there
that you created, and you're adding option_values to it. The problem:
option_values is a tuple, and you can't add a tuple to the end of a list.
Why, you may ask? Because Python isn't sure what the result should be in
such a case: a mutable list, or an immutable tuple? The operations
"foo1.extend(option_values)" or foo1 += option_values would make it very
clear that you're just adding stuff to the end of an existing list. But a +
b returns a /new/ object, and Python won't guess if you want it to be a list
or a tuple.

Now, that said.

The fix is easy. Broken down:

    foo1 = [pkg, prodid, tmpTable, quantity]
    foo2 = foo1 + list(option_values)

    cur.execute(sql, foo2)

Alternately:

    foo1 = (pkg, prodid, tmpTable, quantity)
    foo2 = foo1 + option_values

    cur.execute(sql, foo2)

And then condensed back into a single line:

    cur.execute(sql, [pkg, prodid, tmpTable, quantity] +
list(option_values))

Or:

   cur.execute(sql, (pkg, prodid, tmpTable, quantity) + option_values)

I removed the explicit conversion-to-tuple in the first, because... you
don't need to. Execute takes a sequence. It doesn't have to be a tuple. A
list is fine. In the second one, I just build my first arguments as a tuple
instead of as a list, and then add option_values to it... You'll just have
to go up top and do:

    option_values = ()

In both places where you currently use []. As you can't add a list to a
tuple anymore then a tuple to a list, for the same reasons.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100605/2738f9c9/attachment-0001.html>


More information about the Python-list mailing list