Search code examples
pythonlistunpack

Unpack a single element from a list of lists python


I have zipped some data into as following:

list1 = [1,33,3]
list2 = [2,44,23]
list3 = [[3,4,5,6],[3,4,5,3],[4,5,3,1]]
list4 = [4,34,4]

data = [list(x) for x in zip(list1, list2, list3, list4)]

However, list3 is a list of lists. So the output ended up being

[[1,2,[3,4,5,6],4],
 [33,44,[3,4,5,3],34], 
 [3,23,[4,5,3,1],4]]

I would like to unpack the list inside the lists like the following:

[[1,2,3,4,5,6,4],
 [33,44,3,4,5,3,34], 
 [3,23,4,5,3,1,4]]

What is the best way to do that in python?

Cheers


Solution

  • If only two level-deep, you can try with first principles:

    out = [
        [e for x in grp for e in (x if isinstance(x, list) else [x])]
        for grp in zip(list1, list2, list3, list4)
    ]
    
    >>> out
    [[1, 2, 3, 4, 5, 6, 4], [33, 44, 3, 4, 5, 3, 34], [3, 23, 4, 5, 3, 1, 4]]