Convert a list of tuples to a list of lists in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Check out my new book

Convert a list of tuples to a list of lists in Python #

To convert a list of tuples to a list of lists:

  1. Use a list comprehension to iterate over the list.
  2. Convert each tuple to a list by passing them to the list() class.
  3. The new list will only contain list objects.
main.py
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)
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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:

  1. Pass the list() class and the list of tuples to the map() function.
  2. The map() function will pass each tuple in the list to the list() class.
  3. The new list will only contain list objects.
main.py
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.

If you want to convert the items of the list in place instead of creating a new list of lists, use a for loop.
main.py
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.

Use the search field on my Home Page to filter through my more than 3,000 articles.