list() constructor in Python
Last Updated :
07 Nov, 2024
Improve
In Python list() constructor is a built-in function which construct a list object. We can use list constructor to create an empty list or convert an iterable (dictionary, tuple, string etc.) to a list.
# Example of list constructor
a = list() # creates an empty list
b = list((1, 2, 3)) # covert tuple into list
c = list("GfG") # covert string into list
print(a, type(a))
print(b, type(a))
print(c, type(a))
Output
[] <class 'list'> [1, 2, 3] <class 'list'> ['G', 'f', 'G'] <class 'list'>
Syntax of list()
list([iterable])
We can pass optional argument to list() as iterable. If no iterable is provided, it returns an empty list.
Use of list() constructor
As discussed above, we can create an empty list or convert any iterable to list using list() constructor. Let's see some more examples.
# range() function returns a range object.
# list() can convert this object to a list
a = list(range(3))
print(a)
# Convert a comprehension to list
b = list(x * x for x in range(5))
print(b)
Output
[0, 1, 2] [0, 1, 4, 9, 16]
Creating Nested List with list() constructor
mat = list([list(range(3)) for _ in range(3)])
print(mat)
# output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Shallow copy of List using list()
a = [1, 2, 3]
a1 = list(a)
a1[0] = 5
print(a) # Output: [1, 2, 3]
# different case for Nested List
b = [[1, 2, 3], [4, 5, 6]]
b1 = list(b)
# changing b1 will also reflect in b
b1[0][0] = 10
print(b) # Output: [[10, 2, 3], [4, 5, 6]]