Robert Martin
Robert Martin

Reputation: 17157

In python how can I set multiple values of a list to zero simultaneously?

Conceptually, I want to do:

arr[20:] = 0

where arr is a list. How can I do this?

Upvotes: 31

Views: 112004

Answers (5)

user97370
user97370

Reputation:

You can do it directly using slice assignment.

arr[20:] = [0] * (len(arr) - 20)

But the natural way is just to iterate.

# In Python 2.x, use xrange instead of range
for i in range(20, len(arr)):
    arr[i] = 0

Upvotes: 47

Jian
Jian

Reputation: 209

arr.fill(0)

numpy.ndarray.fill() will fill ndarray with scalar value

Upvotes: 4

Pallapo
Pallapo

Reputation: 1

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.

Upvotes: 0

PaulMcG
PaulMcG

Reputation: 63747

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]

Upvotes: 9

Stephen Oller
Stephen Oller

Reputation: 89

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.

Upvotes: 0

Related Questions