Convert a Tuple of Tuples to a List of Lists in Python

avatar

Borislav Hadzhiev

Last updated: Jul 3, 2022

banner

Check out my new book

Convert a Tuple of Tuples to a List of Lists in Python #

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

  1. Use a list comprehension to iterate over the tuple.
  2. Use the list() class to convert each nested tuple to a list.
  3. The result will be a two-dimensional list.
main.py
tuple_of_tuples = (('one', 'two'), ('three', 'four')) list_of_lists = [list(tup) for tup in tuple_of_tuples] # 👇️ [['one', 'two'], ['three', 'four']] print(list_of_lists)

We used a list comprehension to iterate over the tuple.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the current nested tuple to the list() class to convert it to a list.

The list class takes an iterable and returns a list object.

The result is a two-dimensional list.

Alternatively, you can use the map() function.

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

  1. Pass the list() class and the tuple of tuples to the map() function.
  2. The map() function will pass each nested tuple to the list() class.
  3. Pass the map object to the list class to convert it to a list.
main.py
tuple_of_tuples = (('one', 'two'), ('three', 'four')) list_of_lists = list(map(list, tuple_of_tuples)) # 👇️ [['one', 'two'], ['three', 'four']] 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.

Which approach you pick is a matter of personal preference. I'd go with using a list comprehension as I find it more direct and easier to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.