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

avatar

Borislav Hadzhiev

Last updated: Jul 3, 2022

banner

Photo from Unsplash

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

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

  1. Use a generator expression to iterate over the list.
  2. Use the tuple() class to convert each nested list to a tuple.
  3. Pass the generator object to the tuple() class.
main.py
list_of_lists = [['a', 'b'], ['c', 'd'], ['e', 'f']] tuple_of_tuples = tuple(tuple(l) for l in list_of_lists) # 👇️ (('a', 'b'), ('c', 'd'), ('e', 'f')) print(tuple_of_tuples)

We used a generator expression to iterate over the list.

Generator expressions 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 list to the tuple() class to convert it to a tuple.

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

The last step is to pass the generator object to the tuple() class to convert it to a tuple.

Alternatively, you can use the map() function.

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

  1. Pass the tuple() class and the list of lists to the map() function.
  2. The map() function will pass each nested list to the tuple() class.
  3. Pass the map object to the tuple class to convert it to a tuple.
main.py
list_of_lists = [['a', 'b'], ['c', 'd'], ['e', 'f']] tuple_of_tuples = tuple(map(tuple, list_of_lists)) # 👇️ (('a', 'b'), ('c', 'd'), ('e', 'f')) print(tuple_of_tuples)

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 generator expression.

Notice that we passed the map object to the tuple() class to convert it to a tuple.

Which approach you pick is a matter of personal preference. I'd go with using a generator expression 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.