I’m looking for a single expression, mutates an element and returns the modified list
The following is a bit verbose
# key=0; value=3; rng=[1,2]
[(v if i != key else value) for i, v in enumerate(rng)]
Edit:
I’m looking for a way to inline the following function in a single expression
def replace(rng: List, key: int, value):
a = list(rng)
a[key] = value
return a
>Solution :
Try list concatenation:
key = 0
value = 3
rng = [1, 2]
out = rng[:key] + [value] + rng[key+1:]
print(out)
rng[:key] is a copy of the list up to the key (exclusive), [value] is a new list where the only element is value, and rng[key+1] is a copy of the list from the key on (exclusive). Concatenate these together, and you get a copy where the key is replaced.