This post will discuss how to create an empty list with a given size in Python.

To assign any value to a list using the assignment operator at position i, a[i] = x, the list’s size should be at least i+1. Otherwise, it will raise an IndexError, as shown below:

Download Code

 
The solution is to create an empty list of None when list items are not known in advance. This can be easily done, as shown below:

Download  Run Code

 
The above code will create a list of size 5, where each position is initialized by None. None is frequently used in Python to represent the absence of a value.

 
Another alternative for creating empty lists with a given size is to use list comprehensions:

Download  Run Code

Which solution to use?

The first solution works well for non-reference types like numbers. But you might run into referencing errors in some cases. For example, [[]] * 5 will result in the list containing the same list object repeated 5 times.

Download  Run Code

 
The solution to this problem is using list comprehensions like this:

Download  Run Code

That’s all about creating an empty list with the given size in Python.

 
Also See:

Initialize a list with the same values in Python