Skip to content
Advertisement

How to Remove nested list which is inside a nested list in python?

I want to remove all nested list inside the nested list. Which means

x = [['-e'], ['-d', ['-e'], '-d'], ['-c', ['-d', ['-e'], '-d'], '-c'], ['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b'], ['-a', ['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b'], '-a']]

I want to remove the nested list in index 1,2,3,4… and make it a flat list. To make it clear the below is the separated values in the list.

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

I want it as

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

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

And are there any way to get input like above.

for i in range(0,size):
        z = ['-{}'.format(alnum[size-i])]
        if alnum[size] != alnum[size-i]:
            x.append(z*2)
        else:
            x.append(z)

This was the snippet I used to get that x list.

Advertisement

Answer

With a helper recursive function for flattening nested sublists along with a list comprehension:

def nested_flatten(seq):
    # start with an empty list
    result = []
    
    # for each item in the sublist...
    for item in seq:
        # is item a list?
        if isinstance(item, list):
            # then extend the result with the flattened item
            result += nested_flatten(item)
        else:
            # otherwise extend with the item itself
            result += [item]
    return result

# invoke `nested_flatten` on each sublist
out = [nested_flatten(sub) for sub in x]

to get

>>> out

[['-e'],
 ['-d', '-e', '-d'],
 ['-c', '-d', '-e', '-d', '-c'],
 ['-b', '-c', '-d', '-e', '-d', '-c', '-b'],
 ['-a', '-b', '-c', '-d', '-e', '-d', '-c', '-b', '-a']]
Advertisement