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

Ian Burris picture Ian Burris · May 14, 2011 · Viewed 19.8k times · Source

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?

Answer

Winston Ewert picture Winston Ewert · May 14, 2011

Use a list comprehension:

data = ((1,), (3,))
print([x[0] for x in data])