Convert sql result to list python
When I used the answer from Sudhakar Ayyar, the result was a list of lists, as opposed to the list of tuples created by .fetchall(). This was still not what I wanted. With a small change to his code, i was able to get a simple list with all the data from the SQL query:
cursor = connnect_db()
query = "SELECT * FROM `tbl`"
cursor.execute(query)
result = cursor.fetchall() //result = (1,2,3,) or result =((1,3),(4,5),)
final_result = [i[0] for i in result]
Additionally, the last two lines can be combined into:
final_result = [i[0] for i in cursor.fetchall()]
If you have an iterable in Python, to make a list, one can simply call the list()
built-in:
list(cursor.fetchall())
Note that an iterable is often just as useful as a list, and potentially more efficient as it can be lazy.
Your original code fails as it doesn't make too much sense. You loop over the rows and enumerate them, so you get (0, first_row), (1, second_row)
, etc... - this means you are building up a list of the nth item of each nth row, which isn't what you wanted at all.
This code shows some problems - firstly, list()
without any arguments is generally better replaced with an empty list literal ([]
), as it's easier to read.
Next, you are trying to loop by index, this is a bad idea in Python. Loop over values, themselves, not indices you then use to get values.
Also note that when you do need to build a list of values like this, a list comprehension is the best way to do it, rather than creating a list, then appending to it.
cursor = connnect_db()
query = "SELECT * FROM `tbl`"
cursor.execute(query)
result = cursor.fetchall() //result = (1,2,3,) or result =((1,3),(4,5),)
final_result = [list(i) for i in result]