How to Create List of Zeros in Python
-
Use the
*
Operator to Create a List of Zeros in Python -
Use the
itertools.repeat()
Function to Create a List of Zeros in Python -
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.
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.
LinkedInRelated Article - Python List
- How to Convert a Dictionary to a List in Python
- How to Remove All the Occurrences of an Element From a List in Python
- How to Remove Duplicates From List in Python
- How to Get the Average of a List in Python
- What Is the Difference Between List Methods Append and Extend
- How to Convert a List to String in Python