0

I have a nested list with elements that are lists themselves. I want to find all the sublists and flatten them as a single list:

For example:

[[a], [b,[c,[d,e]]], [f,g]]

I want to have a list containing all existing sublists (flattened) in the original list, that is:

[[a], [b,c,d,e], [c,d,e], [d,e], [f,g]]

I used a recursive function but the problem is that I get nested sublists again which is not what I want. Also my question is not about flattening irregular lists.

3
  • 3
    I wouldn't call this operation "flattening"... in your output e.g. the element d gets duplicated twice. Is that really what you want? Commented Aug 31, 2014 at 18:45
  • @roippi Yes, that's exactly the output I want, I want all occurrences of all the sublists in a single list. Commented Aug 31, 2014 at 18:47
  • No it's not answered! It is not flattening an irregular list. If you see the example output, you understand that it is not flattening. Commented Aug 31, 2014 at 18:54

1 Answer 1

1

We'll use a helper function that returns the flattened form of a nested list and all sublists:

def flattened_list_and_sublists(l):
    # First return value is l, flattened.
    # Second return value is a list of flattened forms of all nested sublists
    # of l.

    flattened = []
    flattened_sublists = []

    for i in l:
        if isinstance(i, list):
            i_flattened, i_flattened_sublists = flattened_list_and_sublists(i)
            flattened += i_flattened
            flattened_sublists.append(i_flattened)
            flattened_sublists += i_flattened_sublists
        else:
            flattened.append(i)
    return flattened, flattened_sublists

Then the function you want returns the second return value of the above function:

def all_flattened_sublists(l):
    l_flattened, l_sublists_flattened = flattened_list_and_sublists(l)
    return l_sublists_flattened
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.