mysqldb cursor.fetchall returns tuple not list

In Python MySQLdb module, cursor.fetchall() returns a tuple. For example:

>>> query = "SELECT name FROM table ..."
>>> cursor.execute(query)
>>> result = cursor.fetchall()
>>> result
(('autos',), ('books',), ('health care products',), ('sports equipment',))

>>>

But often we require the result to be a list instead of tuple. I don't know any straight forward way to do this. So I used the following code:

>>> li = [x[0] for x in result]
>>> li
['autos', 'books', 'health care products', 'sports equipment']
>>>

Please let me know if there is any better way!

Comments

Masnun said…
Hi,

We'd be glad to have you in pycharmers.net - a group of Bangladeshi Python developers.

Nice work! Keep it up vaiya!

-- Masnun
Bryce Verdier said…
Thank you for the blog post. Since you asked for another way to change your tuple of tuples to a list of strings I thought I would offer this up:

>>> from itertools import chain
>>> tt = (('autos',), ('books',), ('health care products',), ('sports equipment',))
>>> list(chain.from_iterator(tt))
['autos', 'books', 'health care products', 'sports equipment']

What you are doing is "flattening" your nested data type. I'm doing the same thing, but just using the "flatten" recipe from itertools. You can read the rest of them here . There are advantages and disadvantages to both, regardless it's good to have more than one tool in your tool box.

Thanks again and keep it up.
Bryce Verdier said…
Thank you for the blog post. Since you asked for another way to change your tuple of tuples to a list of strings I thought I would offer this up:

>>> from itertools import chain
>>> tt = (('autos',), ('books',), ('health care products',), ('sports equipment',))
>>> list(chain.from_iterator(tt))
['autos', 'books', 'health care products', 'sports equipment']

What you are doing is "flattening" your nested data type. I'm doing the same thing, but just using the "flatten" recipe from itertools. You can read the rest of them here . There are advantages and disadvantages to both, regardless it's good to have more than one tool in your tool box.

Thanks again and keep it up.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code