numpy has a function to set the specified elements to be some value
a=numpy.zeros(10)
numpy.put(a, [2,3],1)
However, this method will directly change ‘a’ and return None if succeed.
Is there anyway we can keep ‘a’ intact and return the new array instead?
(I don’t have to use numpy, and least dependency will be more preferred)
Without a function call, and in my opinion somewhat more readable, you can do this:
Note that
a[:]can be very slow for large lists, because – as Makato says – it creates a completely new copy of the list. This is also the reason why numpy ships with the “in situ” (in place) functionput(). If you can, avoid copying the list altogether.To get a sense of the performance, you can think of
a[:]as[i for i in a].I’m not familiar with numpy, so in case I misunderstood and you want to “insert x at positions [a, b, c]”, the other way around, instead, you could do this:
or, alternatively,
Which will be slightly slower.