Borislav Hadzhiev
Last updated: Jul 2, 2022
Check out my new book
To convert a list of tuples to a list of lists:
list()
class.list
objects.list_of_tuples = [('a', 'b'), ('c', 'd'), ('e', 'f')] list_of_lists = [list(tup) for tup in list_of_tuples] # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f']] print(list_of_lists)
In the example, we call the list()
class with each tuple in the list and
return the result.
The list class
takes an iterable (e.g. a tuple) and returns a list
object.
Alternatively, you can use the map()
function.
To convert a list of tuples to a list of lists:
list()
class and the list of tuples to the map()
function.map()
function will pass each tuple in the list to the list()
class.list
objects.list_of_tuples = [('a', 'b'), ('c', 'd'), ('e', 'f')] list_of_lists = list(map(list, list_of_tuples)) # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f']] print(list_of_lists)
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
This approach is a bit more implicit than using a list comprehension.
Notice that we passed the map
object to the list()
class to convert it to a
list.
for
loop.my_list = [('a', 'b'), ('c', 'd'), ('e', 'f')] for index, tup in enumerate(my_list): my_list[index] = list(tup) # 👇️ [['a', 'b'], ['c', 'd'], ['e', 'f']] print(my_list)
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.
On each iteration, we use the index to update the type of the value to a list
object.