In this article, we will discuss different ways to create an empty list with certain size.
Table Of Contents
Introduction
An empty list of size N means, that list will contain N None values. For example, an empty list of size 5 is,
emptyList = [None, None, None, None, None]
There are different ways to create a list of given size and with None values only. Let’s discuss them one by one.
Create an empty list with certain size using astrik
First, create a list with one None value only, and then multiply that with N. Where, N is the size of empty list. It will give us a list with N None values. for example,
N = 5 # Create an empty List of size N emptyList = [None] * N print(emptyList)
Ouput:
[None, None, None, None, None]
It created a list of 5 None values.
Create an empty list with certain size using List Comprehension
Inside a List comprehension, iterate from 0 till N and add None to a list. Where, N is the size of empty list. It will give us a list with N None values. For example,
N = 5 # Create an empty List of size N emptyList = [None for i in range(N) ] print(emptyList)
Ouput:
[None, None, None, None, None]
It created a list of 5 None values.
Summary
We learned how to create an empty list of given size in Python. Thanks.