In numpy this is called fancy indexing . To get the elements you need, you must use an array of 2D indexes.
You can use outer to make a valid 2D index array from your 1D idx . Outers applied to two 1D sequences compare each element of one sequence with each element of the other. Recalling that True*True=True and False*True=False , np.multiply.outer() , which is the same as np.outer() , can give you 2D indices:
idx_2D = np.outer(idx,idx) #array([[ True, False, False, True], # [False, False, False, False], # [False, False, False, False], # [ True, False, False, True]], dtype=bool)
What you can use:
x[ idx_2D ] array([ 1, 4, 13, 16])
In your real code, you can use x=[np.outer(idx,idx)] , but it does not save memory, working just as if you turned on del idx_2D after the slice was executed.
source share