How to Convert Tuple to List in Python:
Tuples and lists are two commonly used data structures in Python. A tuple is an immutable sequence of values, whereas a list is a mutable sequence of values. Sometimes, it may be necessary to convert a tuple to a list or vice versa, In this blog, we will focus on how to convert a tuple to a list in Python.
Method 1: Using the list() Constructor
To convert a tuple to a list in Python by using the list() constructor. The list() constructor takes an iterable as an argument and returns a new list containing all the elements in the iterable.
# create a tuple
my_tuple = (1, 2, 3, 4, 5)
# convert the tuple to a list
my_list = list(my_tuple)
# print the list
print(my_list)
Output:
[1, 2, 3, 4, 5]
In this example, we first create a tuple called my_tuple
containing five integers. We then use the list() constructor to convert the tuple to a list and assign the result to a new variable called my_list
. Finally, we print the contents of the my_list
variable to verify that the conversion was successful.
Method 2: Using a Loop
To convert a tuple to a list is by using a loop to iterate over the tuple's elements and append them to a new list. Here's an example program that demonstrates this approach:
# create a tuple
my_tuple = (1, 2, 3, 4, 5)
# create an empty list
my_list = []
# iterate over the tuple and append each element to the list
for item in my_tuple:
my_list.append(item)
# print the list
print(my_list)
Output:
[1, 2, 3, 4, 5]
In this example, we first create a tuple called my_tuple
containing five integers. We then create an empty list called my_list
and use a for loop to iterate over each element in the tuple. For each element, we append it to the list using the append() method. Finally, we print the contents of the my_list
variable to verify that the conversion was successful.
Method 3: Using the extend() Method
To convert a tuple to a list is by using the extend() method. The extend() method is a built-in method of lists that takes an iterable as an argument and adds all its elements to the end of the list. Here's an example program that demonstrates this approach:
# create a tuple
my_tuple = (1, 2, 3, 4, 5)
# create an empty list
my_list = []
# add all elements of the tuple to the list using the extend() method
my_list.extend(my_tuple)
# print the list
print(my_list)
Output:
[1, 2, 3, 4, 5]
In this example, we first create a tuple called my_tuple
containing five integers. We then create an empty list called my_list
and use the extend()
method to add all elements of the tuple to the list. Finally, we print the contents of the my_list
variable to verify that the conversion was successful.
Comments (0)