How two rows can be swapped in a torch tensor?
var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]

var = torch.Tensor(var)


Here, var is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?

2, -3, 2, 1 
0, 1, -4, 8
5, -8, 7, 1


The other answer does not work, as some dimensions get overwritten before they are copied:
&gt;&gt;&gt; var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]
&gt;&gt;&gt; x = torch.tensor(var)
&gt;&gt;&gt; index = torch.LongTensor([1, 0, 2])
&gt;&gt;&gt; x[index] = x
&gt;&gt;&gt; x
tensor([[ 0,  1, -4,  8],
        [ 0,  1, -4,  8],
        [ 5, -8,  7,  1]])

For me, it suffices to create a new tensor (with separate underlying storage) to hold the result:
&gt;&gt;&gt; x = torch.tensor(var)
&gt;&gt;&gt; index = torch.LongTensor([1, 0, 2])
&gt;&gt;&gt; y = torch.zeros_like(x)
&gt;&gt;&gt; y[index] = x

Alternatively, you can use index_copy_ (following this explanation in discuss.pytorch.org), although I don't see an advantage for either way at the moment.
