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.

Community
  • 1
  • 1
CentAu
  • 10,660
  • 15
  • 59
  • 85
  • 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? – roippi Aug 31 '14 at 18:45
  • @roippi Yes, that's exactly the output I want, I want all occurrences of all the sublists in a single list. – CentAu Aug 31 '14 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. – CentAu Aug 31 '14 at 18:54

1 Answers1

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
user2357112
  • 260,549
  • 28
  • 431
  • 505