In Python, we can easily create a list of zeros. The easiest way to create a list of zeros only is to use the Python * operator.

list_of_zeros = [0] * 10

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

A second way to make a list of zeros in Python is to use a for loop.

list_of_zeros = list(0 for i in range(0,10))

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

Finally, we can create a list of list of zeros using the Python itertools repeat() function.

import itertools

list_of_zeros = list(itertools.repeat(0,10))

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

In Python, creating a list of zeros can be useful if we want to initialize a list to count or fill later on in our program.

There are a number ways that we can create and fill a list with zeros.

The easiest way to create a list with only zeros is to use the * operator on a single item array containing 0.

To get a list of 10 zeros for example, we multiply the single item list by 10.

list_of_zeros = [0] * 10

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

You can use this method to create a list which contains any value as shown below in Python.

list_of_a = ["a"] * 10

print(list_of_a)

#Output:
["a","a","a","a","a","a","a","a","a","a"]

Filling a List With Zeros Using a Loop in Python

Another method to creating a list of zeros is to use a loop in your Python code.

Below shows how you can fill a list with only zeros using a loop in Python.

list_of_zeros = list(0 for i in range(0,10))

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

Making a List With Zeros Using the Python itertools repeat() Function

The Python itertools module is very useful and gives us a number of great functions to work with iterable objects.

We can use the itertools repeat() function to create a list of zeros in Python as shown below.

import itertools

list_of_zeros = list(itertools.repeat(0,10))

print(list_of_zeros)

#Output:
[0,0,0,0,0,0,0,0,0,0]

Hopefully this article has been useful for you to learn how to make a list with only zeros in Python.

Categorized in:

Python,

Last Update: March 18, 2024