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