1

I have sqlite and I query two columns from a table like this:

result_set = conn.execute("SELECT time, MeanCurrent from MEASUREMENTS")

then, I want to put each column into a separate list, what I'm doing so far is this:

list1 = [record[0] for record in result_set]
list2 = [record[1] for record in result_set]

The problem is that, while list1 prints the first column perfectly, list2 appears empty, while, if I remove the first line, list2 prints the second column perfectly as well!

So it's like, after the first line execution, something changes in my query but I don't know what.

Is there any way to deal with this?

1
  • I don't know enough Python to express this with actual syntax, but I would define the arrays, then have a loop to iterate over the result_set and push the fields of the record into the list arrays. Commented Jan 7, 2017 at 16:52

1 Answer 1

3

conn.execute() returns a cursor object. You can't iterate over a cursor more than once; when you reach the end, it won't start at the beginning again when iterating a second time. Either load all rows into a list first, or use a different technique that only needs to iterate once.

I'd use the zip() function to pair up columns:

list1, list2 = zip(*result_set)

but you could use results = list(result_set) or results = result_set.fetchall() to materialise all rows into a list first, or you could use a single loop that uses list1.append() and list2.append() to add the column values to the two lists.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, spent so much time trying to figure this out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.