Search code examples
pythonmap-function

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?


Solution

  • Use a list comprehension:

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