Apply a function on a single element of a tuple

Question:

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

Asked By: BPeif

||

Answers:

Map is what you need. Use it to apply a function on each tuple. That function would only interact with the second number of each tuple

def function(item):
    whatever(item[1])
    return item

data = [(1995, 50.28), (1996, 28.52)]
map(function, data)
Answered By: Portevent

You can use basic "for" loop. You can use like that;

data = [(1995, 50.28), (1996, 28.52)]

for i in range(0,len(data)):
    data[i] = list(data[i])
    data[i][1] = round(data[i][1])
    data[i]=tuple(data[i])
Answered By: statistic

You can do this with a list comprehension and the built-in round() function as follows:

data = [(1995, 50.28), (1996, 28.52)]

result = [(x, round(y)) for x, y in data]

print(result)

Output:

[(1995, 50), (1996, 29)]
Answered By: Cobra

You can use lambda function inside map like this:

result = list(map(lambda x:(x[0], round(x[1])), data))

Output is :

[(1995, 50), (1996, 29)]
Answered By: romain gal

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)]
Answered By: Ignatius Reilly
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.