Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Anyway to use map to get first element of a tuple

I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple ((1,), (3,)). I'd like to do something like set(map([0], ((1,), (3,)))) (where [0] is accessing the zeroth element) to get a set with 1 and 3 in it. The only way I can figure to do it is to define a function: def first(t): return t[0]. Is there anyway of doing this in one line without having to declare the function?

like image 275
Ian Burris Avatar asked May 13 '11 23:05

Ian Burris


People also ask

How do you find the 1st element of a tuple?

We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list. Example: Here we will get the first IE student id from the list of tuples.

How do you get the first part of a tuple in Python?

Use indexing to get the first element of each tuple Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.

How do you access elements in a list of tuples in Python?

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.


4 Answers

Use a list comprehension:

data = ((1,), (3,))
print([x[0] for x in data])
like image 176
Winston Ewert Avatar answered Oct 22 '22 15:10

Winston Ewert


Use operator.itemgetter:

from operator import itemgetter
map(itemgetter(0), ((1,), (3,)))

While the list comprehensions are generally more readable, itemgetter is closest to what you asked for. It's also a bit faster:

>>> from timeit import timeit
>>> setup = 'from operator import itemgetter; lst=( ("a",), ("b",), (1,), (2,))'
>>> timeit('map(itemgetter(0), lst)', setup=setup)
0.13061050399846863
>>> timeit('[i[0] for i in lst]', setup=setup)
0.20302422800159547
like image 34
Steve Howard Avatar answered Oct 22 '22 14:10

Steve Howard


my_set = {x[0] for x in TUPLES}
like image 4
ninjagecko Avatar answered Oct 22 '22 14:10

ninjagecko


Just another way to get it:

set(x for x, in data)
like image 3
neurino Avatar answered Oct 22 '22 16:10

neurino