Convert a List of Lists to a List of Tuples

This tutorial will discuss about unique ways to convert a list of lists to a list of tuples.

Suppose we have a list of lists. Like this,

listOfLists = [['John', 34],
                ['Mark', 23],
                ['Suse', 37],
                ['Avni', 29],
                ['John', 100],
                ['John', 102]]

We want to convert this list of lists into a list of tuples, like this,

[('John', 34),
 ('Mark', 23),
 ('Suse', 37),
 ('Avni', 29),
 ('John', 100),
 ('John', 102)]

For that, we will use the map() function.

Call map() method, and pass following arguments in it,

  • tuple() method. It accepts a sequence as an argument and returns a tuple with the same elements as in the sequence.
  • List of lists.

The map() function will apply the the tuple() method on each list in the tuple. Which will convert each list into a tuple. Then it will store all the converted tuples into a mapped object. Then we can create a list of tuples from the tuples in the mapped object using the list() function.

This way we can convert a list of lists into a list of tuples.

Let’s see the complete example,

# List of Lists
listOfLists = [['John', 34],
                ['Mark', 23],
                ['Suse', 37],
                ['Avni', 29],
                ['John', 100],
                ['John', 102]]

# Convert list of lists to list of tuples
# using map() function
listOfTuples = list(map(tuple, listOfLists))

print(listOfTuples)

Output

[('John', 34), ('Mark', 23), ('Suse', 37), ('Avni', 29), ('John', 100), ('John', 102)]

Summary

We learned how to convert a list of lists to a list of tuples in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top