Python list() Method
The list()
method returns a list object from an iterable passed as arguement with all elements.
Syntax:
list(iterable)
Parameter:
iterable: (Optional) The iterable to be converted into a list.
Return type:
Returns a list.
empty_list = list() # returns empty list
print("Empty list: ", empty_list)
print(type(empty_list))
num_list = list((1,2,3,4,5)) # converts tuple to list
print("tuple to list: ", num_list)
print(type(num_list))
Empty list: []
<class 'list'>
tuple to list: [1, 2, 3, 4, 5]
<class 'list'>
The following example converts other types of iterable string, set, Dictionary to list using the list()
method
print("string to list: ", list('Hello World')) # converts string to list
print("set to list: ", list({1,2,3,4,5})) # converts set to list
print("dictionary to list: ", list({1:'one',2:'two',3:'three'})) # converts dict keys to list
string to list: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
set to list: [1, 2, 3, 4, 5]
dictionary to list: [1, 2, 3]
The list()
method raise an error if passed other type of value instead of iterable.
lst= list(123456)
Traceback (most recent call last):
list(123456)
TypeError: 'int' object is not iterable