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()
print(li)
# []

Using []

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

li = []
print(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
print(li)
# [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
print(li)

li = [3.14] * 5
print(li)

The output of the above code is,

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

Conclusion

Hope this article is helpful. Happy coding!