Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all empty nested lists

How to from this list:

list = [
    [],
    ['', 'subitem'],
    [[]],
    'item',
    [
        'item',
        'item',
        [''],
        []
    ],
    []
]

I can get this:

list = [
    ['subitem'],
    'item',
    [
        'item',
        'item'
    ]
]

How do I remove recursively all empty nested lists, zero-strings, and lists with nested zero-strings?

like image 587
Dmitry Logvinenko Avatar asked Apr 11 '26 13:04

Dmitry Logvinenko


1 Answers

Recursion:

def remove_lst(lst):
    if not isinstance(lst, list):
        return lst
    else:
        return [x for x in map(remove_lst, lst) if (x != [] and x != '')]
like image 68
realli Avatar answered Apr 13 '26 02:04

realli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!