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

4

41

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')]
Redeploy answered 21/9, 2013 at 22:21 Comment(0)
A
68

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')]
Argol answered 21/9, 2013 at 22:23 Comment(1)
What if the level of nesting for each item is unknown? Well, Mr. Pieters already answered this here :)Condillac
E
13

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.

Engagement answered 21/9, 2013 at 22:29 Comment(0)
T
7
[tuple(l) for l in nested_lst]
Thibodeaux answered 21/9, 2013 at 22:24 Comment(0)
R
1

I used list comprehension as a solution , below is my style

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

nested_new_list =[(i,j) for i,j in nested_lst]

print(nested_new_list)

output : [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
Rocketry answered 6/5, 2022 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.