Four Ways To Initialize List With Zeros In Python

Initialize list with zeros in Python

Lists in Python are one of the most used data structures.  In this article, we will first discuss why we should initialize a list with zeros in Python. This will give us an insight into how different ways of creating lists in python can lead to different usage of memory. After that, we will discuss four ways to create list of zeros in python.

Why Initialize List with Zeros in Python?

Generally, we don’t need to initialize lists in Python. We can always declare an empty list and append elements to it later. But this method comes with a drawback.  

In python, lists are implemented in such a way that their size grows automatically. At any instance, the size of the list is almost 1.5 times the number of elements actually present in it. This leads to inefficiency in the program as a large part of allocated memory remains unused. You can understand this using the following program.

Output:

Here, we have created two lists namely list1 and list2 with the same number of elements. The difference lies in how we have created those lists. We have created list1 by declaring an empty list. After that, we have appended five elements to the list. On the contrary, we have created list2 by initializing it directly using all the elements. 

After that, we have used the __sizeof__() method to get the actual size of the list object (not the length). You can easily observe that the memory used by list2 is significantly less than the memory used by list1

In situations where we need to store thousands of elements in a list, a significant amount of memory will be wasted if we use the append() method. So, I would suggest you initialize a list whenever you know the exact number of elements in the list. Let us now discuss how we can initialize a list with zeros in python.

How Can We Initialize List With Zeros In Python?

We can initialize list with zeros in python using the following four ways.

  • By using * operator
  • By using itertools.repeat() function
  • By using generator comprehension
  • By using list comprehension 

Let us now discuss the above ways one by one.

Initialize List With Zeros Using * Operator In Python

The multiplication operator “*” can be used to create new lists from existing lists in python. When we multiply a given list with a number N using the * operator, it creates a new list by concatenating the existing list N number of times. You can observe this in the following example.

Output:

To initialize a list with zeros using the * operator, we will create a list with 0 as its only element. After that, we will multiply the list by the number of elements required in the output list. 

For instance, we can initialize a list with zeros having 10 elements as follows.

Output:

Initialize List With Zeros Using  itertools.repeat() Function

An alternate way to initialize a list with zeros is to use iterators. To initialize a list with zeros, we will create an iterator having 0 as all of its elements. Then, we will create a list from the iterator using the list() function.

To create the iterator, we will use the repeat() function defined in the itertools module. The syntax for the repeat() function is as follows.

itertools.repeat(value,number_of_times_value_is_repeated)

The repeat() function takes the value as its first argument and the number of times the value has to be repeated as its option argument. In case, we don’t provide the second argument i.e. the number of times the given value has to be repeated, an infinite iterator is created.

For instance, To create an iterator with 10 zeros, we will have to use the following statement in python.

After creating the iterator, we can use the list() constructor to initialize the list with zeros as follows.

Output:

Initialize List With Zeros Using  Generator Comprehension In Python

Instead of using iterators, we can also use generators to initialize a list with zeros in python. Here, we will use generator comprehension and the range() function to create a generator. The syntax for generator comprehension is as follows.

generator= (expression for element in iterable)

Here,

  • expression” is the value that will be included in the generator. For us, it will be 0 as we have to create a generator with all zeros.
  • We will create an “iterable” with the number of elements required in the list using the range() function by passing the number of elements required in the generator as input argument. For instance, to create a generator that yields 10 elements, we will give 10 as the input argument to the range() function.

We can create a generator that yields 10 zeros using generator comprehension and the range() function as follows.

After creating the generator, we can initialize the list with zeros using the list() constructor as follows.

Output:

Initialize List With Zeros Using  List Comprehension In Python

Instead of using generator comprehension and the list() constructor, we can directly use list comprehension to initialize a list with zeros in Python. The syntax for list comprehension is as follows.

newList= [expression for element in iterable]

Here, 

  • newList” is the newly created list using list comprehension.
  • expression” is the value that will be included in the newList. For us, it will be 0 as we have to create a list with all zeros.
  • Also, We will create an “iterable” with the number of elements required in the list using the range() function.  We will pass the number of elements required in the list as the input argument to the range() function. For instance, to create a list that has 10 elements, we will give 10 as the input argument to the range() function.

The program to initialize a list with zeros using list comprehension in python is as follows.

Output:

Conclusion

In this article, we have discussed four ways to initialize a list with zeros in python. All of the methods have their own benefits and you can use them at your convenience. Whenever you know the number of elements in the list before defining a list, you can initialize a list with zeros and reassign the values in the list. Even if you don’t need a list having zero as its elements, you can do this. This will help you write an efficient program that will require less memory. 

I hope you had fun reading this article. Stay tuned for informative articles.

Happy Learning!

Related Posts

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • 07 January

    How to compare lists in Python

    Table of ContentsPython compare listsHow to compare lists in PythonUsing the sort() function and == operatorUsing the map() and reduce() functionsUsing the set() function and == operatorUsing the for loopUsing the set() function and - operatorUsing the collections.Counter() class and == operatorUsing the zip(), sum(), and len() functionsUsing the cmp() functionConclusion In this post, we […]

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.