Open In App

How to Initialize a List in Python

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python List is an ordered collections on items, where we can insert, modify and delete the values. Let’s first see how to initialize the list in Python with help of different examples.

Initialize list using square brackets []

Using [] we can initialize an empty list or list with some items.

Python
# Initialize empty list with []
a = []

# adding elements
a = [1, 2, 3, 'List']
print(a)


Using list() constructor to Initialize a List

We can use list() constructor to create and initialize the lists. list() can also convert other iterables to list type.


Python
# initialize list usign list() constructor

# initializing empty list
a = list()

# initializing list with items
a  = ([1, 2, 3])
print(a)


Using list comprehensions to Initialize a List

List comprehension is a more advanced way to create lists in Python. It allows us to create lists in a single line of code.

Python
# using list comprehension to initialize list
a = [i for i in range(1, 6)]
print(a)


Using * operator to Initialize a List

We can also initialize a list with the same value repeated multiple times using * operator.

Python
# use * operator to initialize list
a = [0] * 5
print(a)


Using for loop and append()

for loop method dynamically builds a list by appending elements one by one. We are creating empty list and run a for loop for n times using append() method.

Python
arr = []
for i in range(1000):
    arr.append(0)
print(len(arr))

Output
1000

Above method can be less efficient for large lists due to repeated append() calls.



Next Article
Article Tags :
Practice Tags :

Similar Reads