list() function is used to create a list from iterable objects such as strings, tuples, sets and dictionaries. It converts each element of the iterable into a separate item in the list.
s = "Python"
res = list(s)
print(res)
Output
['P', 'y', 't', 'h', 'o', 'n']
Explanation: list(s) converts each character of the string "Python" into separate elements of a list.
Syntax
list(iterable)
Parameters: iterable (optional) - an object that can be iterated over, such as a string, tuple, set or dictionary.
Returns: A new list containing elements from the iterable. If no argument is provided, it returns an empty list [].
Examples
Example 1: In this example, a tuple containing numbers is converted into a list using the list() function.
tup = (10, 20, 30, 40)
res = list(tup)
print(res)
Output
[10, 20, 30, 40]
Explanation: list(tup) converts all elements of the tuple into a list.
Example 2: Here, the list() function is used to convert dictionary keys into a list.
d = {'A': 10, 'B': 20, 'C': 30}
res = list(d)
print(res)
Output
['A', 'B', 'C']
Explanation: When a dictionary is passed to list(), only the keys are added to the list.
Example 3: This example takes input from the user and converts each character into a list element.
a = list(input("Enter text: "))
print(a)
Output
Enter text: Hello
['H', 'e', 'l', 'l', 'o']
Explanation: list(input()) converts the entered string into a list of individual characters.