Python list()
Function
The list() function in Python is used to create a new list. It can also be used to convert other iterable data types like strings, tuples, or sets into a list.
Syntax
list([iterable])
Parameters:
iterable
(optional) – An iterable object like string, tuple, set, or dictionary.
Returns:
- A new list containing items from the given iterable.
Example 1: Creating an Empty List
my_list = list()
print(my_list)
[]
Example 2: Converting a String to a List
my_list = list("hello")
print(my_list)
['h', 'e', 'l', 'l', 'o']
Example 3: Converting a Tuple to a List
my_list = list((1, 2, 3))
print(my_list)
[1, 2, 3]
Example 4: Converting a Set to a List
my_list = list({10, 20, 30})
print(my_list)
[10, 20, 30]
Example 5: Converting a Dictionary to a List
my_dict = {'a': 1, 'b': 2}
my_list = list(my_dict)
print(my_list)
['a', 'b']
Note: Only the keys of the dictionary are added to the list.
Use Cases
- Convert data types like tuples or sets to a list for modification
- Split a string into a list of characters
- Convert dictionary keys into a list for iteration
Common Mistakes
- list is not a function call: Forgetting parentheses:
my_list = list
assigns the function, not a list. - Non-iterable input:
list(5)
will throwTypeError
becauseint
is not iterable.
Interview Tip
In interviews, the list()
function is often used to convert generators or iterators to lists for easier access and manipulation.
Summary
list()
creates a list from an iterable or creates an empty list.- Commonly used to convert other data types to a list.
- Only iterable objects can be passed.
Practice Problem
Convert the string "Tutorial"
into a list of characters, and print it.
word = "Tutorial"
letters = list(word)
print(letters)