user9440895
user9440895

Reputation:

how to extract all sublists from nested list?

i have a nested list. For example:

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

I want to get a list which contains that list and all sublists separately as elements. So the expected results is:

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

i wrote this function:

def extract(lst):
    result = []
    result.append(lst)
    for i in lst:
        if isinstance(i, list):
            result.append(i)
            extractt(i)
    return result

But the result is not what expected. how could i fix it?

Upvotes: 1

Views: 369

Answers (2)

Qq0
Qq0

Reputation: 946

I believe your code discards the result of the recursive call to extract. You could amend it like so:

def extract(lst):
    result = [lst]
    for i in lst:
        if isinstance(i, list):
            result += extract(i)
    return result

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can use recursion with a generator:

def get_lists(d):
  if isinstance(d, list):
     yield d
     for i in d:
        yield from get_lists(i)

print(list(get_lists(['a', ['b', 'c', ['e', 'd']]])))

Output:

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

Upvotes: 3

Related Questions