Get the first element of each tuple in a list in Python [duplicate]
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?
Solution 1:
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.
Solution 2:
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)
Solution 3:
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]
>>>
Solution 4:
You can use list comprehension:
res_list = [i[0] for i in rows]
This should make the trick