The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Question
00:33 Accepted answer (Score 238)
01:11 Answer 2 (Score 41)
01:24 Answer 3 (Score 24)
01:42 Answer 4 (Score 13)
01:56 Thank you

--

Full question
https://stackoverflow.com/questions/2241...

Accepted answer links:
[list comprehension]: http://docs.python.org/3/tutorial/datast...

Answer 3 links:
[map]: https://docs.python.org/2/library/functi...
[operator.itemgetter]: https://docs.python.org/2/library/operat...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #syntax

#avk47



ACCEPTED ANSWER

Score 246


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.




ANSWER 2

Score 24


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]
>>>



ANSWER 3

Score 13


You can use list comprehension:

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

This should make the trick




ANSWER 4

Score 9


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.