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
4 Answers 4
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
BlackJack
4,7331 gold badge22 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
lightalchemist
10.2k4 gold badges49 silver badges55 bronze badges
Comments
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
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
lang-py