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']

BlackJack
4,7331 gold badge22 silver badges26 bronze badges
asked Aug 24, 2015 at 15:41

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]
answered Aug 24, 2015 at 18:48
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]

answered Feb 26, 2019 at 8:01

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]))
answered Jul 14, 2017 at 9:35

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, [])
answered Feb 26, 2019 at 7:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.