Get the first element of each tuple in a list in Python

Creak picture Creak · Mar 14, 2014 · Viewed 295.1k times · Source

An SQL query gives me a list of tuples, like this:

[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]

I'd like to have all the first elements of each tuple. Right now I use this:

rows = cur.fetchall()
res_list = []
for row in rows:
    res_list += [row[0]]

But I think there might be a better syntax to do it. Do you know a better way?

Answer

user2555451 picture user2555451 · Mar 14, 2014

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.