Home > Software engineering >  How to make convert a tuple within a list within a list to a list?
How to make convert a tuple within a list within a list to a list?

Time:10-02

I am trying to convert a tuple within a list within a list to a list. For example:

a = [[('a', 'b'), ('c', 'd')], [('e', 'f')]]

I need

a = [[['a', 'b'], ['c', 'd']], [['e', 'f']]]

The groups of tuples could be of varied numbers but always at the same level - tuple within a list, within a list.

There are lots of threads about converting tuples to lists but everything I have found are within less lists such as ('a', 'b') or [('a', 'b')] or without variation of list length.

Thank you.

CodePudding user response:

You can use two nested map calls.

b = list(map(lambda nested: list(map(lambda nested2: list(nested2), nested)), a))

Or with list comprehension:

b = [[list(j) for j in i]  for i in a]

CodePudding user response:

This would do what you want:

a = [[('a', 'b'), ('c', 'd')], [('e', 'f')]]

new_a = [ [ list(element) for element in elements] for elements in a]

CodePudding user response:

For this purpose I would suggest you to do a list comprehension as given below:

a = [[('a', 'b'), ('c', 'd')], [('e', 'f')]]

a = [[list(j) for j in i] for i in a]

print(a)

Alternatively, if you are a beginner, you can also use a for loop for this purpose as given below:

a = [[('a', 'b'), ('c', 'd')], [('e', 'f')]]

for i in range(len(a)):
    for j in range(len(a[i])):
        a[i][j] = list(a[i][j])
        
print(a)

Personally, I would suggest you to use list comprehension.

  • Related