How to Create a List of Zeros?

Creating A List Of Zeros (1)

A list of Zeros can be created just like any other list in Python. But we initialize an entire list with zeros in this process. Although this process may not sound helpful, a whole list with zeros can be useful in a few cases.

While working with arrays and matrices and you are unsure of what to initialize them with or you may need to add the elements after the initialization, you may choose to initialize the data structure with zeros and update them later.

This only works if you are dealing with mutable data structures though. If you are dealing with immutable data types like tuples or sets, we cannot change their state after initialization.

Refer to this article to know more about immutable data types.

Another use case is when you have a data structure with a few missing values. If there is no value you can think of to fill in these missing places, you may go for a list of zeros and fill in the missing places. We can update these zeros with values later on. This process helps us to maintain the uniformity of the data structure.

In this article, we are going to learn about the definition of a list with a few examples and explore different approaches to creating a list of zeros.

What Is a List?

A list is the most primal data type of the Python language. It is used to store different elements under a single name. It is similar to an array in other programming languages with a little difference. While a list can store heterogeneous elements, an array can’t.

The elements of the list are enclosed within square brackets. A list is a mutable data type in Python. A mutable data type can be changed after initialization or declaration. At the same time, an immutable data type cannot be changed.

Check out this post to learn more about lists and their characteristics.

Let us see a simple example of a list.

There are multiple ways to create a list. Let us look at creating a list from a dictionary.

Let us take a look at the dictionary.

shopping_cart={'Vegetables':['Egg Plant','Cauliflower','Celery','Peppers','Lettuce'],
               'Fruits':['Mango','Banana','Apple','Cherries'],
               'Milk Products':['Milk','Cottage Cheese','Butter'],
               'Snacks':['Cookies','Chips','Nachos','Chocolates']}
print("The dictionary is:",shopping_cart)
print(type(shopping_cart))

We have created a dictionary called shopping_cart that has the following keys: ‘Vegetables’, ‘Fruits’,’ Milk Products’, ‘Snacks’, and their related keys enclosed in curly braces.

In the next two lines, we are printing the dictionary and also checking the default class of this variable.

The output is given below.

Dictionary
Dictionary

We can convert this dictionary to a list with the help of list() constructor. When we use this constructor, only the keys of the dictionary are returned.

shopping_list=list(shopping_cart)
print("The list of items is:",shopping_list)
type(shopping_list)

We have created a variable called shopping_list to store the keys of the dictionary. We are printing this list and also checking the default class of this variable

List Of Keys
List Of Keys

To obtain the values of this dictionary, we can use extend function. The code is given below.

shopping_list = []
for items in shopping_cart.values():
    shopping_list.extend(items)
print("The list of items is:", shopping_list)
type(shopping_list)

The output is shown below.

List Of Values
List Of Values

How to Create a List of Zeros?

We are going to learn all the possible ways of initializing a list with all zeros. They are all simple and short so make sure to stick till the end!

Using for Loop

The concept is simple. We iterate a for loop until a certain number to generate a list with that number of zeros. Let us see an example.

lsz = []
n = 10 
for _ in range(n):
    lsz.append(0)
print("The list of zeros is:")
print(lsz)

We need to have a list to store the zeros, don’t we?

We are creating an empty list called lsz in the first line. Following that, we are initializing a variable called n to 10. The list we are going to create has 10 zeros.

Then, we are initializing a for loop from 1 through 10. The zeros are appended to the list one by one. Then we are printing the list.

List Of Zeros Using For Loop
List Of Zeros Using For Loop

Using List Comprehension

List comprehension is used to perform operations on lists in a short and sweet way. List comprehension does not take multiple lines of code, one line will do the job.

Refer to this article to know more about list comprehension.

n = 10  
listzeros = [0 for _ in range(n)]
print(listzeros)

In the first line, we are initializing a variable called n with 10 to print 10 zeros in a list.

Next, we are creating a list called listzeros and we are using a list comprehension that inserts 0 for each position until 10.

Lastly, we are printing the list.

List Of Zeros With List Comprehension
List Of Zeros With List Comprehension

List of Zeros With a Function

We can even define a user function that creates a list with all zeros.

def liszeros(n):
  return [0]*n
print("The list of zeros is:")
liszeros(7)

We have created a function called liszeros to initialize a list with zeros.

The return [0]*n prints zeros in the form of a list through the number n.

In the last line, we are calling the function to print the list.

List Of Zeros With User Defined Function
List Of Zeros With User Defined Function

List of Zeros Using Itertools

Itertools is a Python module that is used to perform complex operations on iterations. There is a function called repeat in this module, that returns an object over and over again infinite times, unless specified.

The syntax is given below.

itertools.repeat(object[, times])

The code is given below.

from itertools import repeat
list(repeat(0, 10))

The above code prints a list that contains 10 zeros.

List Of Zeros Using Itertools
List Of Zeros Using Itertools

Conclusion

To conclude, we have learned how a list containing all zeros might come in handy when we are trying to initialize a data structure in uncertain conditions. An all-zero list can also be used to handle missing values.

We have studied the definition of a list and understood how we can generate a list from a dictionary with an example.

Coming to creating a list with zeros we have seen four approaches- A for loop, List comprehension, User-defined function and finally, the itertools module.

All the methods followed the same process. We have created an empty list and appended the required number of zeros to the list using for loop. In the list comprehension, we have done the same thing, but in a single line. Coming to the user-defined function, we have passed the number of zeros we want in the list to the function call. The repeat function of the itertools module is used to return an object based on a condition.

References

Learn more about Itertools here.

Refer to this stack overflow answer chain on the same topic.