Kilgore Trout
Kilgore Trout

Reputation: 49

How to unpack a list inside a list of lists as well as elements?

I have list of lists and variable like this:

a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)], (4,5), (1,2)]

outupt required

a=[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (4,5), (1,2)]

I have tried this solution, but it unpacks everything.

[Unpack list of lists into list

I have also tried to unpack using a for loop wrt indexes. Couldn't make it work.

    for j in range (4):
        if len(a[j])!= 2:
            a[j]=list(itertools.chain(*a[j])

Upvotes: 0

Views: 131

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195418

Here is recursive method to flatten the list (the tuples inside list won't be flattened):

a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)], (4,5), (1,2)]

def flatten(lst):
    for v in lst:
        if isinstance(v, list):
            yield from flatten(v)
        else:
            yield v

print([*flatten(a)])

Prints:

[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (4, 5), (1, 2)]

Upvotes: 2

Related Questions