0

I have a mysql call:

zip = 48326

cursor.execute ("""
    select distinct(name) 
      from usertab 
     where zip= %s
""" , (zip))

result = cursor.fetchall()

The result is returned in a tuple that looks like this:

result = (('alan',), ('bob',), ('steve',), ('tom',))

But I need a list like this:

mylist= ['alan', 'bob', 'steve', 'tom']

So I process the tuple into a list like this:

mylist = []

for row, key in enumerate(result):
    for col, data in enumerate(key):
        mylist.append(data)

This code works, but I'd like a simpler way.
How can I fetch a mysql single column result directly into a list?

1
  • Thanks to Tadeck and Pawelmhm... I compacted my mysql fetch to this: mylist = [row[0] for row in cursor.fetchall()] Commented Jul 11, 2013 at 15:16

2 Answers 2

10

Do it like that, using list comprehension:

mylist = [row[0] for row in result]

It will flatten your result and create list from it.

Another approach, without list comprehension:

from itertools import chain
mylist = list(chain.from_iterable(result))

It will flatten a result and convert it to list.

Sign up to request clarification or add additional context in comments.

Comments

0

75 % of Python question on StackOverflow can be answered with the words: "list comprehension";)

Here is a solution using list comp:

>>> result = (('alan',), ('bob',), ('steve',), ('tom',))
>>> mylist = [i[0] for i in result]
>>> mylist 
['alan', 'bob', 'steve', 'tom']

Please learn more about list comprehension here, it will save you a good deal of time.

3 Comments

First ;) "75 % of Python question on StackOverflow can be answered with the words: "list comprehension";)" - do you have source for that?
Well ok I don't have a source :) but really there is so many questions that can be solved with list comprehension, this tool is really so powerful, and so many people are unaware of it.
Well, in fact, list comprehension is just a shortcut.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.