How to convert nested list of lists into a list of tuples in python 3.3?

Mohammed picture Mohammed · Sep 22, 2013 · Viewed 23.7k times · Source

I am trying to convert a nested list of lists into a list of tuples in Python 3.3. However, it seems that I don't have the logic to do that.

The input looks as below:

>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]

And the desired ouptput should look as exactly as follows:

nested_lst_of_tuples = [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]

Answer

Martijn Pieters picture Martijn Pieters · Sep 22, 2013

Just use a list comprehension:

nested_lst_of_tuples = [tuple(l) for l in nested_lst]

Demo:

>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
>>> [tuple(l) for l in nested_lst]
[('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]