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

Question:

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?

Asked By: Creak

||

Answers:

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.

Answered By: user2555451

You can use list comprehension:

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

This should make the trick

Answered By: Ruben Bermudez
res_list = [x[0] for x in rows]

c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

For a discussion on why to prefer comprehensions over higher-order functions such as map, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.

Answered By: Aegis

If you don’t want to use list comprehension by some reasons, you can use map and operator.itemgetter:

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
Answered By: Jimilian

The functional way of achieving this is to unzip the list using:

sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)

(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)

Answered By: rbonallo
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.