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
We'd be glad to have you in pycharmers.net - a group of Bangladeshi Python developers.
Nice work! Keep it up vaiya!
-- Masnun
>>> 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.
>>> 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.