Rotan075
Rotan075

Reputation: 2615

Get list out of other list

For some reason I end up with having a "list within a list" which does not really make sense to me:

I got a variable which contains the following output:

>>> print(combined_result)
>>> [[('id1', 'titel1'), ('id2', 'titel2'), ('id3', 'titel3'), ('id3', 'titel4')]]

which is generated by the following code:

combined_result = []
def executequery(cursor):
        cursor.execute("SELECT id, title FROM database")
        records = cursor.fetchall()
        result = records
        combined_result.append(result)
        return

To actually get the first element of that combined list I call it with:

>>> print(combined_result[0][1])
>>> ('id1', 'titel1')

I am wondering whether this is the right way to do it? Or should I modify my code? It is a bit weird right to have a list within a list in my situation?

Upvotes: 0

Views: 50

Answers (3)

Brian L
Brian L

Reputation: 3251

Try using extend instead of append - instead of treating the list as a single item to append, it takes all the items of one list and adds them to the other:

combined_result.extend(result)

Upvotes: 1

ForceBru
ForceBru

Reputation: 44926

You just don't need combined_result as result is already a list. You can return result from your function.

combined_result = []
def executequery(cursor):
    cursor.execute("SELECT id, title FROM database")
    return cursor.fetchall()

combined_result=executequery(sth)

Upvotes: 1

Ajay
Ajay

Reputation: 5347

Just after the function add this

>>> combined_result=combined_result[0]

Output

>>> combined_result
[('id1', 'titel1'), ('id2', 'titel2'), ('id3', 'titel3'), ('id3', 'titel4')]

Upvotes: 1

Related Questions