How do I set the first N elements of an array to zero?
I have a long array:
x= ([2, 5, 4, 7, ...])
for which I need to set the first N
elements to 0
. So for the N = 2
desired output would be:
x = ([0, 0, 4, 7, ...])
Is there an easy way to do this in Python? Some function numpy
?
Pure python:
x[:n] = [0] * n
with numpy:
y = numpy.array(x)
y[0:n] = 0
also note that x[:n] = 0
does n't work if x
is a python list (instead of a numpy array).
It's also a good idea to use [{some object here}] * n
for any mutable, because there won't be n different objects in the list, but n references to the same object:
>>> a = [[],[],[],[]]
>>> a[0:2] = [["a"]] * 2
>>> a
[['a'], ['a'], [], []]
>>> a[0].append("b")
>>> a
[['a', 'b'], ['a', 'b'], [], []]
Just set them explicitly:
x[0:2] = 0