In this Python article we want to learn How to Convert Python Tuples to Lists, Python is powerful programming language that provides developers with different builtin data structures. two commonly used data structures in Python are tuples and lists. while tuples are immutable and ordered sequences of elements, lists are mutable and can be changed as needed. in this article we want to discuss how to convert tuples to lists in Python.
How to Convert Python Tuples to Lists
For converting tuple to list we can use builtin list() function. list() function takes any iterable object as input and returns a list containing all the elements of the iterable object.
This is an example of how to convert a tuple to a list
1 2 3 4 5 6 7 8 |
# Define 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) |
In this example we have defined a tuple called my_tuple with five elements. after that we have converted tuple to a list using the list() function and assign the result to a variable called my_list. and lastly we print the contents of the list using the print() function.
This will be the result
If we have a tuple that contains other tuples, we can convert the nested tuples to nested lists using a list comprehension. list comprehension is a way to create new list based on an existing iterable object.
This is an example of how to convert nested tuples to nested lists using list comprehension
1 2 3 4 5 6 7 8 |
# Define nested tuple nested_tuple = ((1, 2), (3, 4), (5, 6)) # Convert nested tuple to a nested list nested_list = [list(t) for t in nested_tuple] # Print the nested list print(nested_list) |
In this example we have defined nested tuple called nested_tuple that contains three tuples with two elements each. after that we have used a list comprehension to convert each nested tuple to nested list and assign the result to a variable called nested_list. and lastly we print the contents of the nested list using the print() function.
This will be the result