How to declare array of zeros in python (or an array of a certain size)


Question

I am trying to build a histogram of counts... so I create buckets. I know I could just go through and append a bunch of zeros i.e something along these lines:

buckets = []
for i in xrange(0,100):
    buckets.append(0)

Is there a more elegant way to do it? I feel like there should be a way to just declare an array of a certain size.

I know numpy has numpy.zeros but I want the more general solution

1
164
12/18/2014 12:03:52 PM

Accepted Answer

334
5/28/2019 9:11:08 PM

Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

buckets = [[0 for col in range(5)] for row in range(10)]

to avoid reference sharing between the rows.

This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon