Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert sql result to list python

Tags:

python

sql

mysql

im beginner with python.I want to convert sql results to a list.Here's my code:

cursor = connnect_db()

query = "SELECT * FROM `tbl`"

cursor.execute(query)

options = list()

for i,row in enumerate(cursor.fetchall()):
   options.append(row[i])

There is 6 column in my table but this code doesn't create 6 element-list.Where am i doing wrong?

like image 227
saidozcan Avatar asked Feb 12 '13 15:02

saidozcan


1 Answers

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.

like image 118
Gareth Latty Avatar answered Sep 28 '22 08:09

Gareth Latty