How do I set the first N elements of an array to zero?
2 answers
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'], [], []]
+11
source to share