[Newbie] Strange output from list

Chris Rebert clp at rebertia.com
Tue Nov 11 04:20:05 EST 2008


On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <nospam at nospam.com> wrote:
> On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <alif016 at gmail.com> wrote:
>>sql = 'SELECT id FROM master'
>>rows=list(cursor.execute(sql))
>>for id in rows:
>>       sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
>>       result = list(cursor.execute(sql))
>>       print "Code=%s, number=%s" % (id[0],result[0][0])

Using liberal "term rewriting", consider the following rough
equivalencies in the code:

id[0] <==> rows[INDEX_HERE][0] <==> list(cursor.execute(sql))[INDEX_HERE][0]
result[0][0] <==> list(cursor.execute(sql))[0][0]

Note that in both cases, the list is sliced twice; the for-loop just
conceals the `[INDEX_HERE]` implicit slicing that is caused by
iterating over the list.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>>Notice the extra [0] index on the "result"
>>
>>In English:
>>Item zero of the tuple that is item zero of result
>
> Thanks, it worked. But why does "id[0]" return the value of the first
> (and only) column as I expected it, while I need to use "result[0]
> [0]" to access the first column?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list