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

29,039

Solution 1

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')]

Solution 2

You can use map():

>>> list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))
[('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]

This is equivalent to a list comprehension, except that map returns a generator instead of a list.

Solution 3

[tuple(l) for l in nested_lst]
Share:
29,039
Mohammed
Author by

Mohammed

Ph.D. Student in Computational Linguistics, Central Institute of Indian Languages, Mysore - India.

Updated on December 07, 2020

Comments

  • Mohammed
    Mohammed over 3 years

    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')]
    
  • z33k
    z33k over 2 years
    What if the level of nesting for each item is unknown? Well, Mr. Pieters already answered this here :)