Conceptually, I want to do:
arr[20:] = 0
where arr
is a list
.
How can I do this?
You can make a function that you will pass the array to that will zero out the array. I haven't used Python in a while, so I won't attempt to show you the Python code. In that function you could use a for
or while
loop to iterate through each value and setting each one equal to zero.
If you use list comprehension you make a copy of the list, so there is memory waste. Use list comprehension or slicing to make new lists, use for cicles to set your list items correctly.
arr.fill(0)
numpy.ndarray.fill() will fill ndarray with scalar value
You can do it directly using slice assignment.
arr[20:] = [0] * (len(arr) - 20)
But the natural way is just to iterate.
for i in xrange(20, len(arr)):
arr[i] = 0
Here are a couple of options:
List comprehension
>>> a = [1]*50
>>> a = [aa if i < 20 else 0 for i,aa in enumerate(a)]
>>> a
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
List slice assignment:
>>> a = [1]*50
>>> a[20:] = [0 for aa in a[20:]]
>>> a
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Zip(*zip):
>>> a = [1]*50
>>> a[20:] = zip(*zip(a[20:],itertools.repeat(0)))[1]