1

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?

2 Answers 2

3

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']]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.