Select unindexed rows

I would like to select the rows which are not indexed by a indexing list, such as:

x = torch.randn(10)
indexing_list = torch.LongTensor([2,5])
x[-indexing_list] # What I want to do: remove out rows which are not indexed, thus there remains 8 items

anyone has a good idea?

BTW, is it faster to use LongTensor as an indexing list or maybe just same as np.array and primitive list?

Not knowing precisely the use case, I’d suggest something like: (i) transform your undesired indexes in a set, (ii) construct a list of the complement of your indexes.

 python -m timeit --setup="import torch;x = torch.rand(10 ** 5);not_idx = set(torch.randint(10 ** 5, (10 ** 5,)).tolist())" "x[[e for e in range(10 ** 5) if e not in not_idx]]"

The step e not in not_idx is very fast in python.

Do you mean

import torch

x = torch.randn(10)
indexing_list = [2,5]
index = torch.ones(x.shape[0], dtype=bool)
index[indexing_list] = False
selected_x = x[index]
print(selected_x)

Indeed, this is faster than what I’ve suggested:

python -m timeit --setup="import torch;x = torch.rand(10 ** 5);not_idx = torch.randint(10 ** 5, (10 ** 5,))" "idx = torch.ones(10 ** 5).bool(); idx[not_idx] = False; x[idx]"