0

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?

Rotan075
  • 2,567
  • 5
  • 32
  • 54

3 Answers3

1

Just after the function add this

>>> combined_result=combined_result[0]

Output

>>> combined_result
[('id1', 'titel1'), ('id2', 'titel2'), ('id3', 'titel3'), ('id3', 'titel4')]
Ajay
  • 5,267
  • 2
  • 23
  • 30
1

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)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

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)
Brian L
  • 3,201
  • 1
  • 15
  • 15
  • what is the difference between extend and append? – Rotan075 Apr 22 '15 at 06:52
  • I described the difference in my answer - `append` treats the list as a single item; `extend` treats the list as multiple items. See also http://stackoverflow.com/questions/252703/python-append-vs-extend – Brian L Apr 22 '15 at 09:13