22

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3059201
  • 775
  • 2
  • 7
  • 11
  • 2
    How about `x[:N] = 0`, if it's actually a `numpy` array? – jonrsharpe Jun 25 '15 at 11:52
  • Indexing and assigning is covered pretty thoroughly in NumPy's [documentation](http://docs.scipy.org/doc/numpy/user/basics.indexing.html). – Alex Riley Jun 25 '15 at 11:54
  • possible duplicate of [Python/Numpy: Setting values to index ranges](http://stackoverflow.com/questions/20812787/python-numpy-setting-values-to-index-ranges) – jhoepken Jun 25 '15 at 11:55

2 Answers2

40

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'], [], []]
syntonym
  • 7,134
  • 2
  • 32
  • 45
5

Just set them explicitly:

x[0:2] = 0
jhoepken
  • 1,842
  • 3
  • 17
  • 24