Python Exercise: Convert a given list of tuples to a list of lists
33. Convert a List of Tuples to a List of Lists
Write a Python program to convert a given list of tuples to a list of lists.
Sample Solution:
Python Code:
# Define a function named 'test' that takes a list of tuples 'lst_tuples' as input.
def test(lst_tuples):
# Use a list comprehension to convert each tuple in 'lst_tuples' to a list.
result = [list(el) for el in lst_tuples]
# Return the resulting list of lists.
return result
# Create a list of tuples 'lst_tuples' containing tuples of integers.
lst_tuples = [(1, 2), (2, 3), (3, 4)]
# Print a message indicating the original list of tuples.
print("Original list of tuples:")
print(lst_tuples)
# Print a message indicating the conversion of the list of tuples to a list of lists.
# Call the 'test' function to perform the conversion and print the result.
print("Convert the said list of tuples to a list of lists:")
print(test(lst_tuples))
# Create another list of tuples 'lst_tuples' with a different set of tuples, including varying numbers of elements.
lst_tuples = [(1, 2), (2, 3, 5), (3, 4), (2, 3, 4, 2)]
# Print a message indicating the original list of tuples.
print("\nOriginal list of tuples:")
print(lst_tuples)
# Print a message indicating the conversion of the list of tuples to a list of lists.
# Call the 'test' function to perform the conversion and print the result.
print("Convert the said list of tuples to a list of lists:")
print(test(lst_tuples))
Sample Output:
Original list of tuples: [(1, 2), (2, 3), (3, 4)] Convert the said list of tuples to a list of lists: [[1, 2], [2, 3], [3, 4]] Original list of tuples: [(1, 2), (2, 3, 5), (3, 4), (2, 3, 4, 2)] Convert the said list of tuples to a list of lists: [[1, 2], [2, 3, 5], [3, 4], [2, 3, 4, 2]]
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to convert each tuple in a list into a list using list comprehension.
- Write a Python program to iterate over a list of tuples and construct a new list of lists from them.
- Write a Python program to implement a function that takes a list of tuples and returns a list where each tuple is converted to a list.
- Write a Python program to use map() to transform a list of tuples into a list of lists.
Python Code Editor:
Previous: Write a Python program to compute the sum of all the elements of each tuple stored inside a list of tuples.
Next: Python Sets Exercise Home.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.