I have a long array:
x= ([2, 5, 4, 7, ...])
for which I need to set the first N
elements to 0
. So for N = 2
, the desired output would be:
x = ([0, 0, 4, 7, ...])
Is there an easy way to do this in Python? Some numpy
function?
Pure python:
x[:n] = [0] * n
with numpy:
y = numpy.array(x)
y[:n] = 0
also note that x[:n] = 0
does not work if x
is a python list (instead of a numpy array).
It is also a bad idea to use [{some object here}] * n
for anything mutable, because the list will not contain n different objects 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With