Assuming you want to replace for example each 4 with a 16.

Edit: you could also do this with a tensor, but you would need to do it like tensor[tensor==4] = sixteens_tensor.clone() if you want to do it in autograd on a leaf variable. Also the sixteens_tensor must contain exactly as many values as there are 4s in tensor

This definitely looks cleaner! But I don’t have a sense of how much more efficient it is. It looks like it though.
Also I dont want to modify the original tensor. So will need to make a clone() first.

I don’t think you will see much differences there regarding the performance.

Note: if you want to replace the 4s by arbitrary values defined in a tensor, I would recommend masked_scatter_ instead of looping over tensors yourself. This approach should also work with a tensor of always the same value (e.g. always 16). However, this function will also modify the original tensor. If you don’t want this behavior, you would also need to clone it before.

@justusschock Thanks.
Is there a batch way to replace several particular values? for example, old_new_value = [[2,22],[3,33]], which means 2 should be replaced by 22, and 3 should be replaced by 33.
Can I have a efficient way to achieve this ? Thank you.