Which one is better ? In term of memory, execution time, idiomatic, …

I would call the second approach much more idiomatic, and it should be more efficient in terms of computational efficiency (“compute”) and memory consumption. The reason is that it wouldn’t make sense to use a Python list if you want something to be in a fixed-size array later on. A list would be super inefficient because it would allocate more memory on the fly when you append and it’s running out of allocated memory, and in the worst case, it can allocate approx twice as memory as needed. Btw. in your case, I would probably also specify the dtype in torch.empty_like.
If you can, the ideal way regarding computing and memory resources would be to modify/override the values in the input tensor directly instead of creating a second tensor (output), but it’s only possible if the input entries don’t overlap between the different computations you perform via fn