Python is a popular programming language that offers a wide range of built-in functions to perform various tasks. One of the most commonly used built-in functions is "list()", which creates a new list object.
The "list()" function can be used to create a new list object from an existing iterable object such as a string, tuple, or another list. It takes an iterable object as its argument and returns a list containing the elements of the iterable object.
Syntax: The syntax for the "list()" function is as follows:
|
list(iterable)
|
where:
Example 1:
|
my_string = "Hello World"
my_list = list(my_string)
print(my_list)
|
In this example, we have created a string "my_string" with the value "Hello World". We then use the "list()" function to convert the string into a list and assign it to the variable "my_list". We then print the value of "my_list". The output of this code will be:
Output:
|
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
|
|
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list)
|
In this example, we have created a tuple "my_tuple" with the values 1, 2, 3, 4, and 5. We then use the "list()" function to convert the tuple into a list and assign it to the variable "my_list". We then print the value of "my_list". The output of this code will be:
Output:
|
[1, 2, 3, 4, 5]
|
|
my_list_1 = [1, 2, 3]
my_list_2 = [4, 5, 6]
my_list = list(my_list_1 + my_list_2)
print(my_list)
|
In this example, we have created two lists "my_list_1" and "my_list_2" with the values 1, 2, 3 and 4, 5, 6 respectively. We then concatenate both the lists using the "+" operator and pass the result to the "list()" function to create a new list "my_list". We then print the value of "my_list". The output of this code will be:
Output:
|
[1, 2, 3, 4, 5, 6]
|
|
my_string = "Hello World"
my_list = list(my_string)
my_list[0] = 'J'
print(my_list)
|
In this example, we have created a string "my_string" with the value "Hello World". We then use the "list()" function to convert the string into a list and assign it to the variable "my_list". We then update the first element of "my_list" to 'J'. We then print the value of "my_list". The output of this code will be:
Output:
|
['J', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
|