List initialization in python

In this article we shall see how to initialise an empty list or a list of size n initialised with a value. The list initialisation can be done in the following ways.

Using the list()

We can directly initialise a list using the list() keyword. This will create an empty list for us.

li = list()
# []

Using []

We can also declare an empty list directly using the brackets.

li = []
# []

Initialise list with values

We can also initialise a list with some default values. All we have to do is create a list with the value we want and multiply it by the required value.

li = [0]*10
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This works not only with integers but also with any data type.

li = ['str'] * 5

li = [3.14] * 5

The output of the above code is,

['str', 'str', 'str', 'str', 'str']
[3.14, 3.14, 3.14, 3.14, 3.14]


Hope this article is helpful. Happy coding!