Get the first element of each tuple in a list in Python
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping
--
Chapters
00:00 Get The First Element Of Each Tuple In A List In Python
00:25 Accepted Answer Score 246
00:54 Answer 2 Score 13
01:05 Answer 3 Score 9
01:21 Answer 4 Score 24
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/2241...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python27 #syntax
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping
--
Chapters
00:00 Get The First Element Of Each Tuple In A List In Python
00:25 Accepted Answer Score 246
00:54 Answer 2 Score 13
01:05 Answer 3 Score 9
01:21 Answer 4 Score 24
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/2241...
--
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.