[Python] fetchall() returns a list of lists instead of a list

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    This is, I'm sure, a very basic SQL question, but I've been unable to determine the cause/solution.

    I have Python code that queries a DB to return a list of categories:

    category_query = "SELECT cat_name FROM categories"
    cursor = mydb.cursor()
    cursor.execute(category_query)
    result = cursor.fetchall()


    The result, when printed from Python code, is:

    [('blob',), ('Clothes',), ('Decorating',), ('Dolls',), ('Household',), ('Kids',), ('Kitchen',), ('Office',), ('Uncategorized',)]


    What I was expecting was:

    [('blob'), ('Clothes'), ('Decorating'), ('Dolls'), ('Household'), ('Kids'), ('Kitchen'), ('Office'), ('Uncategorized')]


    This is easy enough to "fix" by iterating through the results and turning them into a list

    cat_list = []
    for i in categories:
    cat_list.append(i[0])
    categories = cat_list`


    but I'd rather understand why I'm getting this result and how to rewrite the query so that it returns a list instead of a list of lists.

    Continue reading...

Compartilhe esta Página