Scatter homogenous list of values to PyTorch tensor
Consider the following list:

[[3], [1, 2], [4], [0], [2]]


And zeros tensor of size (5, 5)

I want to fill these indices according to their index in the list to the tensor with 1. 

So, the expected output should be:

tensor([[0., 0., 0., 1., 0.],
        [0., 1., 1., 0., 0.],
        [0., 0., 0., 0., 1.],
        [1., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0.]])


What happened above is this:

at the index [0, 3] put 1 (the case for the first element in my list). 



A very similar case is achievable through using Tensor.scatter_. However, since it takes a tensor as the argument (index); you cannot create a tensor from a list if it contains a sub-list with a different size than the other elements, which is the case with [1, 2] in my list (this is actually the problem). 

The scatter method could be used if the list is all of same size as the following:

tensor.scatter_(1, torch.tensor(index), 1)




Numpy solutions are acceptable

You can solve this by modifying your index list to have the same number of indices in each element.



max_length = max([len(l) for l in index])
index = [l + l[-1:] * (max_length - len(l)) for l in index]


This code will repeat the last element of each sub-list until they are all the same size. You can then pass it to the scatter_ function as you wrote in your question.
