[Newbie] Strange output from list

Andrew alif016 at gmail.com
Mon Nov 10 21:02:39 EST 2008


Ben Finney wrote:
> Gilles Ganault <nospam at nospam.com> writes:
>
>   
>> Hello
>>
>> I'm getting some unwanted result when SELECTing data from an SQLite
>> database:
>>
>> ======
>> 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])
>> ======	
>> Code=0111Z, number=(47,)	
>> ======
>>
>> I expected to see "number=47". Why does Python return "(47,)"?
>>     
>
> The result of an SQL SELECT is a sequence of tuples, where each item
> in the tuple is a value for a column as specified in the SELECT
> clause.
>
> SQLAlchemy represents this with a sequence of ResultProxy objects.
> When you convert a ResultProxy object to a string, it displays like a
> tuple. See the documentation for other ways of accessing various
> attributes of a ResultProxy object.
>   
(47,) is the python representation of a one item tuple
If you want:
Code=0111Z, number=47

Just change your code to:
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])
Notice the extra [0] index on the "result" 

In English:
Item zero of the tuple that is item zero of result

E.g.
>>> result = [(47,)]
>>> result = result[0]
>>> result
(47,)
>>> result[0]
47
--
Andrew




More information about the Python-list mailing list