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

  • 06 October

    How to find index of all occurrences in list in Python

    Table of ContentsThe easiest method – Using list count() methodThe Basic Method – Using for loopsThe shortest method – Using the enumerate() functionThe fastest method – Using a numpy arrayUsing itertools moduleUsing more-itertools LibraryUsing index() function List is a data type in Python. It is used to store multiple values in one variable. If you […]

  • Convert list to matrix in Python
    21 August

    Convert list to matrix in Python

    Table of ContentsUsing the while loop to convert list to matrix in Python.Use the numpy.array() method to convert list to matrix in Python.Using the numpy.asarray() method to convert list to matrix in Python. Python provides some in-built data types to stock multiple items in a single variable. A List is one among these built-in data […]

  • Sort list alphabetically in Python
    31 May

    Sort list alphabetically in Python

    Table of ContentsUse of the sort() function to sort list alphabetically in Python.Use of the sorted() function sort list alphabetically in Python.Use of the QuickSort algorithm sort list alphabetically in Python. 💡 Outline You can use sort() method of list to sort list alphabetically in Python [crayon-6180b81c8cf3b649688120/] In this tutorial, we will discuss different ways […]

  • Find common elements in two lists Python
    25 May

    Find common elements in two lists in python

    Table of ContentsUsing the intersection() FunctionUsing List ComprehensionUsing & Operator 💡 Outline You can first convert first list into set using set() and call intersection() by passing second list as parameter to find common element in two lists in Python. [crayon-6180b81c8da9f042648136/] In this tutorial, we will see different methods to find common elements in two […]

  • 11 April

    Python Remove Newline from List

    Table of ContentsIntroduction✨ Method 1: Using the replace() method✨ Method 2: Using re.sub()✨ Method 3: Using strip()✨ Method 4: Slice the List Elements✨ Method 5: Using List Comprehension and Splitlines Function✨ Method 6: Using str.maketrans(x,y) and str.translate(map)Conclusion 🎯 Objective: In this article, we will discuss the methods to remove ‘\n’ or newline characters from a […]

  • 06 April

    Print Matrix in Python

    In this article you will learn "How to print a matrix in Python?"

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.