3

I am working on a program where we have have a certain list with a lot of extraneous nesting, which we want to simplify.

For example, one input could be

[[['A', [[[[[[[[[['B', [[[[[[[[[['C', [[[[[[[[[['D']], [['E']], [['F', [[[[[[[[[['G']]]]]]]]]]]], [['H']], [['I']], [['J']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

and it should output ['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]

However, after running my code, it is not doing anything and returning [].

Here is my code:

def clean_list(list2):
    for item in list2:
        if isinstance(item, list) and len(list2)==1: # this is an extraneous list!
            item = clean_list(item)
            list2.append(item[0].copy())
            list2.remove(item)
    return list2
  • This question was asked few times. Take a look at https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – Yuri Ginsburg Sep 01 '19 at 06:28
  • Possible duplicate of [What is the fastest way to flatten arbitrarily nested lists in Python?](https://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python) – Guy Sep 01 '19 at 06:29
  • 1
    Possible duplicate of [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – shaik moeed Sep 01 '19 at 06:31
  • @shaikmoeed no it's not a duplicate. I don’t want it flattened, just the arbitrary nesting removed – Vidur Gupta Sep 01 '19 at 06:33

1 Answers1

4

You can use a function that recursively de-nests each item in the given list, but passes the sub-list to the recursive call if the list has only one item and that item is a list:

def denest(lst):
    if isinstance(lst, list):
        if len(lst) == 1 and isinstance(lst[0], list):
            return denest(lst[0])
        return [denest(i) for i in lst]
    return lst

so that given your sample list stored in variable lst, denest(lst) would return:

['A', ['B', ['C', [['D'], ['E'], ['F', ['G']], ['H'], ['I'], ['J']]]]]
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 4
    I was writing the exact same code (token-for-token, just with a better naming ;-) ) ... good you were faster than the huge swarm of "bad duplication closing" police :-) – 6502 Sep 01 '19 at 06:44