How to retrieve python list of SQLAlchemy result set?

Question:

I have the following query to retrieve a single column of data:

routes_query = select(
    [schema.stop_times.c.route_number],
    schema.stop_times.c.stop_id == stop_id
).distinct(schema.stop_times.c.route_number)
result = conn.execute(routes_query)

return [r['route_number'] for r in result]

I am wondering if there is a cleaner way to retrieve a native list of the data rows returned.

Asked By: Gavin Schulz

||

Answers:

the most succinct way to pull out a list of 1-element tuples into a list is:

result = [r[0] for r in result]

or:

result = [r for r, in result]
Answered By: zzzeek

This is what I would use:

return zip(*result)[0]

It’s more succinct that the the list comprehension methods in zzzeek’s answer (22 characters rather than 29 or 31 characters), and for larger result sets the timings in this answer to a similar question show that it’s faster too.

Answered By: markshep
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.