2

I want to make a list with the results from a SQL query in Python.

After execution of:

rows = cursor.fetchall()
result_list = [row for row in rows]
print result_list

I am getting output as: [('a',),('b',),('c',)]

I need the output as: ['a','b','c']

4 Answers 4

5

The result list contains tupels with one element. You have to get this element out of each tupel:

result = [row[0] for row in rows]
Sign up to request clarification or add additional context in comments.

Comments

2
import itertools
rows = cursor.fetchall()
result_list = list(itertools.chain(*rows))

This works even when each row contains more than one element.

For example, if rows = [('a', 1), ('b', 2), ('c', 3)], this will produce ['a', 1, 'b', 2, 'c', 3]

Comments

0

The above did not work for me. My solution to it was the following.

list_res = []
for row in rows:
    list_res.append(str(row[0]))

Comments

-1

For python 3 I have simple solution:

sql_data = cursor.fetchall()
python_list = []
for row in sql_data:
    python_list.append(row)
refactor_from_sql_to_list = [list(i) for i in sql_list]
final_list = sum(refactor_from_sql_to_list, [])

Comments

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.