0

I understand nested list comprehension, but searched to see if it were possible to use nested list comprehension to separate the list in individual items on something like this: list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]] I have not found anything online about it.

This was my idea:

def foo(x):
    for a in x:
        for b in a:
            if type(b) != list:
                unpacked = [b for a in x for b in a]
            if type(b) == list:
                unpacked.append(*b)

    return unpacked

However, the output is this: [1, 2, 3, 10, 11, 12, 100, 111, 112, 1, 10, 11, [1000101], 1000101]

Deltag0ny
  • 11
  • 3
  • so you want to flatten the list? – Andrew Ryan Oct 05 '22 at 23:11
  • Yeah, exactly, I didn't know that term. – Deltag0ny Oct 05 '22 at 23:15
  • The solution to this is a bit ugly. This was already asked at least 2 times and both questions have multiple answers: https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists https://stackoverflow.com/questions/12472338/flattening-a-list-recursively – Larry Oct 05 '22 at 23:17

2 Answers2

0

something like this?

    def foo(x):
        unpacked = []
        for a in x:
            unpacked.extend(
                [b for b in a]
            )
        return unpacked
    list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]
    print(foo(list1))
0

Try this:

def unpacklist(list):
    alist = []
    a = 0
    for sublist in list:
        try:
            for i in sublist:
                alist.append(i)
        except TypeError:
            alist.append(sublist)
    for i in alist:
        if type(i) == type([]):
            a += 1
            break
    if a == 1:
        return unpacklist(alist)
    if a == 0:
        return alist

list = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]

a = unpacklist(list)

print(a)
freemangifts
  • 144
  • 6