Declare Python Array of Zeros

How to Declare a Python Array of Zeros?

I’m trying to build a histogram and need to create an array of zeros with a specific size. Currently, I’m using a loop to append zeros like this:

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

Is there a more elegant way to declare an array of zeros in Python, without using numpy.zeros? I’d like a more general solution.

Hey, I’ve worked with histograms quite a bit, and here’s a much simpler approach to declaring a python array of zeros. You can use list multiplication, which is concise and quite efficient.

buckets = [0] * 100

This creates a list of 100 zeros in just one line. It’s neat, and there’s no loop clutter in your code.

Good suggestion! Another way you might consider, especially if you want a bit of flexibility down the line, is to use the map function. I’ve found it helpful when you might want to tweak the initialization logic.

buckets = list(map(lambda x: 0, range(100)))

Using map() isn’t just another way to declare a python array of zeros—it can easily scale if you decide to initialize your list with more complex logic later on. For instance, you could replace the lambda with a custom function.

Both solutions above are great! If you’re working with larger arrays, though, you might want to explore itertools.repeat(). It’s particularly efficient for generating a fixed number of identical elements.

import itertools
buckets = list(itertools.repeat(0, 100))

The advantage here is that itertools.repeat doesn’t immediately create the entire list in memory, which can be handy for larger datasets. Plus, it keeps the implementation clean and Pythonic. It’s another great way to initialize a python array of zeros efficiently.