Skip to Content

How To Create A List Of Zeros (Code Examples)

How To Create A List Of Zeros (Code Examples)

Creating a list in Python can be super easy, but how do you populate that list with a bunch on zeroes?

Python For Loop Example
Python For Loop Example

To create a list of zeroes in Python use the syntax [0] * n where n represents the number of items needed to create the list of zeroes required.

Here’s an example demonstrating this use:

>>> my_zeros_list = [0] * 5
>>> print(my_zeros_list)
[0, 0, 0, 0, 0]

As you can see from the above example the list containing five elements are all populated with the value of 0.

If the requirement were to create a list of 10 zeroes then you would modify the multiplier to suit: my_zeros_list = [0] * 10.

The same technique can similarly be applied should the need by populating a list with empty strings or None datatypes or even ones.

Here are some additional examples demonstrating this fact:

>>> my_empty_strings_list = [""] * 3
>>> print(my_empty_strings_list)
["", "", ""]
>>> my_none_list = [None] * 4
>>> print(my_none_list)
[None, None, None, None]
>>> my_ones_list = [1] * 5
>>> print(my_ones_list)
[1, 1, 1, 1, 1]

As you can see from the examples above it doesn’t matter what you want to populate your list with it can easily be achieved by initialising your list with the item needed and applying the multiplication operator followed by the desired number of elements needed in your list.

The same technique can be applied should there be a recurring pattern in your list as well.

Suppose you needed to populate a list with a zero and an empty string, you could create something like this:

>>> my_zero_string_list = [0, ""] * 2
>>> print(my_zero_string_list)
[0, "", 0, ""]

Regardless of the elements in the initial list if a multiplier is used the initial elements will be repeated according to that multiplier.

This is a great and easy way to create a populated list whether it be zeroes or something else in Python.

Summary

To create a list in Python with a defined set of elements being the same, such as 0, create the list containing the item to be copied and use the multiplication operator followed by a number to represent the number of items you want the initial item to be copied throughout the remainder of the list.

The simple operation is defined as follows in Python: [0] * n with n representing the number of items in your list.