Flatten nested lists when list contains 1 single item which is another list

Basically what I am trying is seeing if I can flatten down nested lists when the list contains 1 single item which is another list. For example take this data structure:

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

The ideal format of the data would be:

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

This nesting can go any amount of levels deep but just need to flatten out single list data. Anyone know a way of doing this? The closest I got with answers on SO was: Flattening a list recursively But this completely flattens the list as a whole.

728x90

2 Answers Flatten nested lists when list contains 1 single item which is another list

A recursive function can do this:

def flatten(l: list):
    if len(l) == 1:
        if isinstance(l[0], list):
            l = l[0]
    for i, elem in enumerate(l):
        if isinstance(type(elem), list):
            l[i] = flatten(elem)
    return l

2 weeks ago

You can use a recursive function that specifically tests if there's only one item in the given list and if that one item is a list, and if so, skips yielding that list:

def simplify(l):
    if len(l) == 1 and isinstance(l[0], list):
        yield from simplify(l[0])
    else:
        for i in l:
            yield list(simplify(i)) if isinstance(i, list) else i

so that:

list(simplify([['a', 'b', 'c', [['d', 'e', 'f']]]]))

returns:

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

2 weeks ago