AmeyA
AmeyA

Reputation: 15

python - how to convert a nested list to a list of all individual sub-lists

I have a Nested List like this:

l = [['A', ['A', 'B', ['A', 'B', 'C'], ['A', 'B', 'D']], ['A', 'D', ['A', 'D', 'A']], ['A', 'C', ['A', 'C', 'B'], ['A', 'C', 'A']], ['A', 'A', ['A', 'A', 'D']]]]

I want to separate it to a List of all individual lists like this:

k = [['A'], ['A', 'B'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'D'], ['A', 'D', 'A'], ['A', 'C'], ['A', 'C', 'B'], ['A', 'C', 'A'], ['A', 'A'], ['A', 'A', 'D']]

I tried this by creating the following function:

def un_nest(l):
    k=[]
    for item in l:
        if type(item) is list:
            un_nest(item)
        else:
            k+=[item]
    print(k)

I got the required output, but I don't know how to convert it to list. the output I got is:

['A', 'B', 'C']
['A', 'B', 'D']
['A', 'B']
['A', 'D', 'A']
['A', 'D']
['A', 'C', 'B']
['A', 'C', 'A']
['A', 'C']
['A', 'A', 'D']
['A', 'A']
['A']
[]

this was output in the shell, (I know this is because of print function), but i have no idea how to get the list from this. As I need to do some operation the the required list for final output. I am using Python 3.4.1 Any hint will help. Thanks in advance

Edit: Its more like I want to, separate all the strings and sub-list from 'l', to another list.

Upvotes: 0

Views: 1010

Answers (1)

ryanpattison
ryanpattison

Reputation: 6251

You could return a list as the result at the current nesting level and join together the nested results using extend.

l = [['A', ['A', 'B', ['A', 'B', 'C'], ['A', 'B', 'D']], ['A', 'D', ['A', 'D', 'A']], ['A', 'C', ['A', 'C', 'B'], ['A', 'C', 'A']], ['A', 'A', ['A', 'A', 'D']]]]

def un_nest(l):
    r = []
    k = []
    for item in l:
        if type(item) is list:
            r.extend(un_nest(item))
        else:
            k.append(item)
    if k:
        r.insert(0, k)
    return r

print(un_nest(l))

outputs:

[['A'], ['A', 'B'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'D'], ['A', 'D', 'A'], ['A', 'C'], ['A', 'C', 'B'], ['A', 'C', 'A'], ['A', 'A'], ['A', 'A', 'D']]

Upvotes: 8

Related Questions