Create an empty list of specific size in Python
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:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [] a[0] = 1 print(a) # raise IndexError: list assignment index out of range |
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:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [None] * 5 print(a) # prints [None, None, None, None, None] |
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:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [None for x in range(5)] print(a) # prints [[], [], [], [], []] |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [[]] * 5 a[0].append(1) print(a) # prints [[1], [1], [1], [1], [1]] |
The solution to this problem is using list comprehensions like this:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [[] for x in range(5)] a[0].append(1) print(a) # prints [[1], [], [], [], []] |
That’s all about creating an empty list with the given size in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)