How to return back a list instead of tuple in psycopg2

When you have more then one rows you can use the following code

result = [r[0] for r in cur.fetchall()]

As a quick fix you can return an array:

cursor.execute("""
    select array_agg(transform(row_to_json(t)))
    from (
        select * from table 
        where a = %s and b = %s
        limit 1000
    ) t;
""", (a_value, b_value))

As Psycopg adapts Postgresql arrays to Python lists then just get that list:

records = cursor.fetchall()[0][0]

I guess it is possible to subclass cursor to return lists in instead of tuples but if you are not dealing with huge sets I think it is not worth the trouble.


you may also use this code

result = cur.fetchall()
x = map(list, list(result))
x = sum(x, [])