How to Create List of Zeros in Python

Manav Narula Feb 02, 2024
  1. Use the * Operator to Create a List of Zeros in Python
  2. Use the itertools.repeat() Function to Create a List of Zeros in Python
  3. Use the for Loop to Generate a List Containing Zeros
How to Create List of Zeros in Python

In this tutorial, we will introduce how to create a list of zeros in Python.

Use the * Operator to Create a List of Zeros in Python

If we multiple a list with a number n using the * operator, then a new list is returned, which is n times the original list. Using this method, we can easily create a list containing zeros of some specified length, as shown below.

lst = [0] * 10
print(lst)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Note that this method is the most simple and fastest of all.

Use the itertools.repeat() Function to Create a List of Zeros in Python

The itertools module makes it easier to work on iterators. The repeat() function in this module can repeat a value a specified number of times. We can use this function to create a list that contains only zeros of some required length when used with the list() function. For example,

import itertools

lst = list(itertools.repeat(0, 10))
print(lst)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Use the for Loop to Generate a List Containing Zeros

The for loop can be used to generate such lists. We use the range function to set the start and stop positions of the list. Then we iterate zero the required number of times within the list() function. Such one-line of code where we iterate and generate a list is called list comprehension. The following code implements this and generates the required list:

lst = list(0 for i in range(0, 10))
print(lst)

Or,

lst = [0 for i in range(0, 10)]
print(lst)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Note that this method is the slowest of them all when generating huge lists.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python List