Sometimes we may be given a python list whose elements are tuples. Then we may have a data processing requirement which will need these tuples to be converted to lists for further processing. In this article, we will see how to convert a list of tuples to a list of lists.
With list comprehension
It is a straight forward approach where we create a for loop to loop through each element and apply the list function to create a list of lists.
Example
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] # Given list print("Given list : \n", listA) res = [list(ele) for ele in listA] # Result print("Final list: \n",res)
Output
Running the above code gives us the following result −
Given list : [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] Final list: [['Mon', 3], ['Wed', 4], ['Fri', 7, 'pm']]
With map and list
In another approach we can use the map function along with list function in. The list function is applied to every element fetched form the outer list and a final list function is applied to the resulting list.
Example
listA = [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] # Given list print("Given list : \n", listA) res = list(map(list, listA)) # Result print("Final list: \n",res)
Output
Running the above code gives us the following result −
Given list : [('Mon', 3), ('Wed', 4), ('Fri', 7, 'pm')] Final list: [['Mon', 3], ['Wed', 4], ['Fri', 7, 'pm']]