Search code examples
pythonlistfunctiontuplesapply

Apply a function on a single element of a tuple


With a direct example it would be easier to understand

data = [(1995, 50.28), (1996, 28.52)]
result = [(1995, 50), (1996, 29)]

I would like to apply a transformation only on the second number of each tuple (50.28 and 28.52).

I saw the map() function that could help, but i think it works only on ALL elements, and having tuples inside list makes it a bit tricky


Solution

  • The more intuitive solution would be to iterate through the elements of the list, as many other answers noticed.

    But if you want to use map, you can indeed but you need first to define a function that applies your desired transformation to the second element of each tuple:

    data = [(1995, 50.28), (1996, 28.52)]
    
    def round_second(tup):
        return tup[0], round(tup[1])
    
    result = list(map(round_second, data))
    result
    >>> [(1995, 50), (1996, 29)]