Search code examples
pythonlist-comprehension

Removing empty sublists from nested list


How do I get from this:

a = [[[1, 1], [], [2,2]], [[2,2], [], [1, 1]]]

to this:

a = [[[1,1], [2,2]], [[2,2], [1,1]]]

quickly? I am trying to use a list comprehension but can't figure it out.


Solution

  • You can use a list comprehension:

    a = [[sublst for sublst in lst if sublst] for lst in a]
    

    Otherwise you can use the filter function:

    [list(filter(None, lst)) for lst in a]