Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set first N elements of 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 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?

like image 945
user3059201 Avatar asked Jun 25 '15 11:06

user3059201


2 Answers

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'], [], []]
like image 173
syntonym Avatar answered Sep 18 '22 18:09

syntonym


Just set them explicitly:

x[0:2] = 0
like image 27
jhoepken Avatar answered Sep 17 '22 18:09

jhoepken