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

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Photo from Unsplash

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

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

  1. Use a list comprehension to iterate over the list.
  2. Convert each nested list to a tuple by passing them to the tuple() class.
  3. The new list will only contain tuple objects.
main.py
list_of_lists = [['a', 'b'], ['c', 'd']] list_of_tuples = [tuple(l) for l in list_of_lists] # 👇️ [('a', 'b'), ('c', 'd')] print(list_of_tuples)
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 tuple() class with each nested list and return the result.

The tuple class takes an iterable (e.g. a list) and returns a tuple object.

Alternatively, you can use the map() function.

To convert a list of lists to a list 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. The new list will only contain tuple objects.
main.py
list_of_lists = [['a', 'b'], ['c', 'd']] list_of_tuples = list(map(tuple, list_of_lists)) # 👇️ [('a', 'b'), ('c', 'd')] print(list_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 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 tuples, use a for loop.
main.py
my_list = [['a', 'b'], ['c', 'd']] for index, l in enumerate(my_list): my_list[index] = tuple(l) # 👇️ [('a', 'b'), ('c', 'd')] 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 tuple object.

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.