473,789 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[Newbie] Strange output from list

Hello

I'm getting some unwanted result when SELECTing data from an SQLite
database:

======
sql = 'SELECT id FROM master'
rows=list(curso r.execute(sql))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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,)"?

Thank you.
Nov 11 '08 #1
12 1595
Gilles Ganault <no****@nospam. comwrites:
Hello

I'm getting some unwanted result when SELECTing data from an SQLite
database:

======
sql = 'SELECT id FROM master'
rows=list(curso r.execute(sql))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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.

--
\ “What is it that makes a complete stranger dive into an icy |
`\ river to save a solid gold baby? Maybe we'll never know.” —Jack |
_o__) Handey |
Ben Finney
Nov 11 '08 #2
My apologies, my response was rather confused.

Ben Finney <bi************ ****@benfinney. id.auwrites:
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.
This remains true. No matter how many columns you specify in the
SELECT clause, each result row is a tuple.
SQLAlchemy represents this with a sequence of ResultProxy objects.
I mistakenly assumed you are using SQLAlchemy, which on re-reading
your post doesn't seem likely.

Instead, by the standard library ‘sqlite3’ module, you will receive
each result row as an ‘sqlite3.Row object:

A Row instance serves as a highly optimized row_factory for
Connection objects. It tries to mimic a tuple in most of its
features.

It supports mapping access by column name and index, iteration,
representation, equality testing and len().

<URL:http://docs.python.org/library/sqlite3.html#ro w-objects>

Since you only asked for the row to be printed, you therefore got a
string representation of the entire row (which mimics a Python tuple,
but is actually a different class with more functionality).

--
\ “Geeks like to think that they can ignore politics. You can |
`\ leave politics alone, but politics won't leave you alone.” |
_o__) —Richard Stallman, 2002-07-26 |
Ben Finney
Nov 11 '08 #3
Ben Finney wrote:
Gilles Ganault <no****@nospam. comwrites:

>Hello

I'm getting some unwanted result when SELECTing data from an SQLite
database:

======
sql = 'SELECT id FROM master'
rows=list(curs or.execute(sql) )
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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(curso r.execute(sql))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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

Nov 11 '08 #4
Andrew <al*****@gmail. comwrites:
(47,) is the python representation of a one item tuple
It's also the representation of a one-column result row, which is more
pertinent here.

Just because ‘str(foo) == str(bar)’, does *not* necessarily mean
‘type(foo) == type(bar)’, nor even ‘isinstance(f oo, type(bar))’.

It's important to know that result rows are *not* tuples, and that
they have different (and more flexible) semantics.

--
\ “To succeed in the world it is not enough to be stupid, you |
`\ must also be well-mannered.” —Voltaire |
_o__) |
Ben Finney
Nov 11 '08 #5
On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <al*****@gmail. comwrote:
>sql = 'SELECT id FROM master'
rows=list(curs or.execute(sql) )
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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
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?
Nov 11 '08 #6
On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <no****@nospam. comwrote:
On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <al*****@gmail. comwrote:
>>sql = 'SELECT id FROM master'
rows=list(cur sor.execute(sql ))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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
Nov 11 '08 #7
Chris Rebert wrote:
On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <no****@nospam. comwrote:
>On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <al*****@gmail. comwrote:
>>sql = 'SELECT id FROM master'
rows=list(cur sor.execute(sql ))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(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.
You might also want to consider saving some time by using a SQL solution
(assuming SQLite supports it, which it should) (untested):

cursor.execute( """
SELECT master.id, count(companies .code)
FROM master JOIN companies ON master.id = companies.code
GROUP BY companies.code" "")
for id, count in cursor.fetchall ():
print "Code=%s, number=%s" % (id, count)

I'd like to think it makes the Python a bit more readable too ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Nov 11 '08 #8
On Nov 11, 10:47*pm, Steve Holden <st...@holdenwe b.comwrote:
Chris Rebert wrote:
On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <nos...@nospam. comwrote:
On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <alif...@gmail. comwrote:
sql = 'SELECT id FROM master'
rows=list(curs or.execute(sql) )
for id in rows:
* * * sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
* * * result = list(cursor.exe cute(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.

You might also want to consider saving some time by using a SQL solution
(assuming SQLite supports it, which it should) (untested):

cursor.execute( """
SELECT master.id, count(companies .code)
* *FROM master JOIN companies ON master.id = companies.code
* *GROUP BY companies.code" "")
Shouldn't it be GROUP BY master.id? I would have thought that SQL
would be sad about a non-aggregate (master.id) that's in the SELECT
list but not also in the GROUP BY list.
for id, count in cursor.fetchall ():
* *print "Code=%s, number=%s" % (id, count)

I'd like to think it makes the Python a bit more readable too ...
Agreed. result[0][0] is an abomination.

Nov 11 '08 #9
John Machin wrote:
On Nov 11, 10:47 pm, Steve Holden <st...@holdenwe b.comwrote:
>Chris Rebert wrote:
>>On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <nos...@nospam. comwrote:
On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <alif...@gmail. comwrote:
sql = 'SELECT id FROM master'
rows=list(c ursor.execute(s ql))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.exe cute(sql))
print "Code=%s, number=%s" % (id[0],result[0][0])
Using liberal "term rewriting", consider the following rough
equivalenci es 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.
You might also want to consider saving some time by using a SQL solution
(assuming SQLite supports it, which it should) (untested):

cursor.execute ("""
SELECT master.id, count(companies .code)
FROM master JOIN companies ON master.id = companies.code
GROUP BY companies.code" "")

Shouldn't it be GROUP BY master.id? I would have thought that SQL
would be sad about a non-aggregate (master.id) that's in the SELECT
list but not also in the GROUP BY list.
Well, I did say "untested". But in SQL Server, for example, any field
argument to COUNT() must be an aggregated column. So it may depend on
the SQL implementation. I should really have said

GROUP BY master.id, companies.code

which is the kind of stupidity SQL's brainless implementations force one
to resort to.
>for id, count in cursor.fetchall ():
print "Code=%s, number=%s" % (id, count)

I'd like to think it makes the Python a bit more readable too ...

Agreed. result[0][0] is an abomination.
Though one I am sure we have all used at times. The original code wasn't
too bad for a beginner.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Nov 11 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
5569
by: John | last post by:
Hello. I am currently working through a book on Dreamweaver and using PHP. I am having a little trouble with setting up the database though. I have php 4.2.3 and MySQL 4.0.20a. I am running locally with Apache 1.3.27 on Windows XP Pro. I seem to have finally got MySQL running after a lot of difficulty. In the book it says to type source C:\mysql\newland_tours.sql at the mysql> prompt, to generate the newland_tours database in my...
13
1434
by: John | last post by:
Hi all: In my code I define a class with inline constructor. But it does not work. I describe the class as below: myclass{ public: myclass(int a, int b) { r1 = a; r2 = b;} protected:
4
6106
by: Oz | last post by:
This is long. Bear with me, as I will really go through all the convoluted stuff that shows there is a problem with streams (at least when used to redirect stdout). The basic idea is that my application (VB.NET) will start a process, redirect its stdout and capture that process' output, displaying it in a window. I've written a component for this, and a test application for the component. It allows me to specify a command to execute,...
8
1831
by: grundmann | last post by:
Hello, i got a strange compiler error. When compiling the following: // forward declarations typedef AvlTree<LineSegment,LineSegmentComperator> LSTree; void handleEventPoint (const EventPoint& , LSTree& , double&, std::list<IntersectionPoint>& );
5
3110
by: Ian | last post by:
Hi everyone, I have found some bizarre (to me...!) behaviour of the Form_Activate function. I have a form which has a button control used to close the form and a subform with a datasheet view showing a list of jobs from the database. When the main form loses focus and the user clicks the 'Close' button, I kept receiving error 2585 (This action cannot be carried out whilst processing a form or report event). This was tracked down to...
4
1601
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I have just started building an application which is windows form based, rather than web based, and I am having troubles with layout. I can't find any control which gives me just a simple text list! There is ListView, but that gives me very strange spacing, perhaps because it is trying to put in icons? There are Flow and Table layout panels, but those also give me strange spacing. I just want the Windows Form Equivalent of an HTML...
2
1002
by: Ken D'Ambrosio | last post by:
First, apologies for such a newbie question; if there's a better forum (I've poked around, some) feel free to point it out to me. Anyway, a mere 25-odd years after first hearing about OOP, I've finally decided to go to it, by way of Python. But this puzzles me: import commands free = commands.getoutput("free") for line in free: print line,
10
1998
by: len | last post by:
I have created the following program to read a text file which happens to be a cobol filed definition. The program then outputs to a file what is essentially a file which is a list definition which I can later copy and past into a python program. I will eventually expand the program to also output an SQL script to create a SQL file in MySQL The program still need a little work, it does not handle the following items
6
11497
Markus
by: Markus | last post by:
Things to discuss: Headers What are they? What does PHP have to do with headers? Why can they only be sent before any output? Common causes
0
9663
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6765
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4090
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.