Create List of Zeros in Python

  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

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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Reverse a List in Python
  • Convert a List to String in Python