The Python Oracle

How to get first element in a list of tuples?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping

--

Chapters
00:00 How To Get First Element In A List Of Tuples?
00:22 Answer 1 Score 25
00:56 Accepted Answer Score 354
01:03 Answer 3 Score 101
01:29 Answer 4 Score 19
01:59 Thank you

--

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

--

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

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 354


>>> a = [(1, u'abc'), (2, u'def')]
>>> [i[0] for i in a]
[1, 2]



ANSWER 2

Score 101


Use the zip function to decouple elements:

>>> inpt = [(1, u'abc'), (2, u'def')]
>>> unzipped = zip(*inpt)
>>> print unzipped
[(1, 2), (u'abc', u'def')]
>>> print list(unzipped[0])
[1, 2]

Edit (@BradSolomon): The above works for Python 2.x, where zip returns a list.

In Python 3.x, zip returns an iterator and the following is equivalent to the above:

>>> print(list(list(zip(*inpt))[0]))
[1, 2]



ANSWER 3

Score 25


do you mean something like this?

new_list = [ seq[0] for seq in yourlist ]

What you actually have is a list of tuple objects, not a list of sets (as your original question implied). If it is actually a list of sets, then there is no first element because sets have no order.

Here I've created a flat list because generally that seems more useful than creating a list of 1 element tuples. However, you can easily create a list of 1 element tuples by just replacing seq[0] with (seq[0],).




ANSWER 4

Score 19


This is what operator.itemgetter is for.

>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b
[1, 2]

The itemgetter statement returns a function that returns the element at the index that you specify. It's exactly the same as writing

>>> b = map(lambda x: x[0], a)

But I find that itemgetter is a clearer and more explicit.

This is handy for making compact sort statements. For example,

>>> c = sorted(a, key=operator.itemgetter(0), reverse=True)
>>> c
[(2, u'def'), (1, u'abc')]