numpy function to set elements of array to a value given a list of indices

involucelate picture involucelate · Dec 4, 2011 · Viewed 21.1k times · Source

I'm looking for a numpy function that will do the equivalent of:

indices = set([1, 4, 5, 6, 7])
zero    = numpy.zeros(10)
for i in indices:
    zero[i] = 42

Answer

stranac picture stranac · Dec 4, 2011

You can just give it a list of indices:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42