Apply function to one element of a list in Python

Posted by user189637 on Stack Overflow See other posts from Stack Overflow or by user189637
Published on 2010-04-02T06:09:20Z Indexed on 2010/04/02 6:13 UTC
Read the original article Hit count: 203

Filed under:
|
|

I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python.

For example, for the following input:

inp = ("hello", "my", "friend")

I would like to be able to get the following output:

out = ("hello", "MY", "friend")

I came up with two solutions which I'm not satisfied with.

One uses a higher-order function.

def apply_at(arr, func, i):
    return arr[0:i] + [func(arr[i])] + arr[i+1:]

apply_at(inp, lambda x: x.upper(), 1)

One uses list comprehensions (this one assumes the length of the tuple is known).

[(a,b.upper(),c) for a,b,c in [inp]][0]

Is there a better way? Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about list