views:

96

answers:

3

it's annoying how sqlite always returns a list of touples! i can see the why this is necessary, but when i am querying a single column, how do i get a plain list?

e.g cursor.fetchall() returns [(u'one',), (u'two',), (u'three',)]

from this, how do i get the simple list [u'one', u'two', u'three']?

+3  A: 
data=cursor.fetchall()
COLUMN = 0
column=[elt[COLUMN] for elt in data]

(My previous suggestion, column=zip(*data)[COLUMN], raises an IndexError if data is an empty tuple. In contrast, the list comprehension above just creates an empty list. Depending on your situation, raising an IndexError may be preferable, but I'll leave that to you to decide.)

unutbu
Idiom or gimmick? Is it robust? For what values of len(foo) is zip(*foo) guaranteed not to go splat?
John Machin
perfect. `columnlist = list(zip(*cursor.fetchall())[COLUMN_INDEX])`
Jeremiah Rose
Jeremiah I think you should pay attention to ~unutbu's warning!
Matt Joiner
i think a bit of a race condition occurred here with the typing of our responses. they're all out of order! both ~unutbu's and my answer (below) work well.
Jeremiah Rose
A: 

account for the case where cursor.fetchall() returns an empty list:

try:
    columnlist = list(zip(*cursor.fetchall())[COLUMN_INDEX])
except IndexError:
    columnlist = []
Jeremiah Rose
+3  A: 

You don't really want to do this - anything you do along the lines of using zip or a list comprehension is just eating CPU cycles and sucking memory without adding significant value. You are far better served just dealing with the tuples.

As for why it returns tuples, it's because that is what the Python DBD API 2.0 requires from fetchall.

Nick Bastin