Last Updated : 07 Nov, 2024
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.
Python
# 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))
[] <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() constructorAs discussed above, we can create an empty list or convert any iterable to list using list() constructor. Let's see some more examples.
Python
# 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)
[0, 1, 2] [0, 1, 4, 9, 16]
Creating Nested List with list() constructor
Python
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()
Python
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]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4