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
Edit 2: the code that actually motivated this question
class TextDecoder(nn.Module):
def forward(self, x: Tensor, kv_cache: Tensor):
kv_cache_write = torch.zeros((_:=list(kv_cache.shape))).__setitem__(-2, x.shape[-1]) or _)
...
replacefunction? Depending on that context, we might still be able to do better than the current answers.t.insert(h+i,t.pop(h+i)|x[i])nor therng.insert(key, rng.pop(key) or value)return the mutated list, they just mutate it...kv_cache_write = torch.zeros(list(kv_cache.shape))kv_cache_write[-2] = x.shape[-1].kv_cache_write, kv_cache_write[-2] = torch.zeros(list(kv_cache.shape)), x.shape[-1]. But I think I'd only really do that when the target name and the expressions are shorter than that. Here I'd prefer the standard two-liner.