Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove any empty list present in the list

I have a list:

i = [[1,2,3,[]],[],[],[],[4,5,[],7]]

I want to remove all the empty list:

[[1,2,3],[4,5,7]]

How can I do this?

Here is my code:

res = [ele for ele in i if ele != []]
like image 839
Avan Wansing Avatar asked May 27 '21 05:05

Avan Wansing


People also ask

How do you remove all the empty list in a list?

Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x] to filter the list.

How do I remove a list from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How to remove empty list from a list of lists in Python?

Python provides its users with in-built functions on data structures to perform the task easily. On such method is filter() method. Syntax: filter(function, iterable) Program to remove the empty list from a list of lists using filter() method

How to add non-empty elements to an empty string?

The empty string "" contains no characters and empty elements could be None or [ ], etc. Simple examples code. Simp;e iterate through the list and add the non-empty elements. Just filter out the None and empty element form list.

How do I filter out empty elements from a list?

Just filter out the None and empty element form list. If None is used as the first argument to filter (), it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

How to filter out blank or empty cells in Excel?

Here the FILTER function will take the range B5:B14 and checks any blanks between the range. Then it filters out empty or blank cells from the list. Press the ENTER key and you will see the list of names without any blanks. But if you go to the Drop Down List, you will still see that it contains blanks from column C.


2 Answers

Use a recursive function to remove the empty list from a list.
Using recursion you can remove an empty list to any depth:

def remove_nested_list(listt):
    for index, value in enumerate(reversed(listt)):
        if isinstance(value, list) and value != []:
            remove_nested_list(value)
        elif isinstance(value, list) and len(value) == 0:
            listt.remove(value)


a = [[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]]
print(f"before-->{a}")
remove_nested_list(a)
print(f"after-->{a}")

Output:

before-->[[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]]
after-->[[1, 2, 3, 0], [4, 5, 7]]
like image 114
Muhammad Safwan Avatar answered Oct 18 '22 20:10

Muhammad Safwan


To remove empty lists from the arbitrarily nested list. We can use recursion here. Here's a simple way to do it. We need to iterate through the list and check if an element is an empty list. If yes, then we don't add it to the final list. If it's not an empty list we repeat the above process.

def remove_empty(lst):
    return (
        [remove_empty(i) for i in lst if i!=[]]
        if isinstance(lst, list)
        else lst
    )

Output:

i = [[1, 2, 3, []], [], [], [], [4, 5, [], 7]]
print(remove_empty(i))
# [[1, 2, 3], [4, 5, 7]]

# Example taken from iGian's answer 
ii = [[1, 2, 3, []], [], [], [], [4, 5, [], 7, [8, 9, [], [10, 11, []]]]] 
print(remove_empty(ii))
# [[1, 2, 3], [4, 5, 7, [8, 9, [10, 11]]]]

To check if an object is iterable we use collection.abc.iterable

from collections.abc import Iterable
all(
    isinstance(i, Iterable)
    for i in ([], tuple(), set(), dict(), range(10), (_ for _ in range(10)))
)
# True

Now, you can replace isinstance(lst, list) with isinstance(lst, Iterable) to filter out empty list i.e [] from every iterable.

Edit:

@Teepeemm pointed out a wonderful corner-case which all the answers missed.

To solve it we need two recursive functions one for checking if it's an empty nested list and the second one for remove empty nested lists

def empty(lst):
    if lst == []:
        return True
    elif isinstance(lst, list):
        return all(empty(i) for i in lst)
    else:
        return False

def remove_empty(lst):
    return (
        [remove_empty(i) for i in lst if not empty(i)]
        if isinstance(lst, list)
        else lst
    )

i = [[1, 2, 3, [[]]]] 
remove_empty(i)
# [[1, 2, 3]]
remove_nested_list(i) # Muhammad Safwan's answer
print(i) # [[1, 2, 3, []]]

ii = [[1, 2, 3, [[], [[[[], []]]]]]]
remove_empty(ii)
# [[1, 2, 3]]
remove_nested_list(ii) # Muhammad Safwan's answer
print(ii) # [[1, 2, 3, [[[[]]]]]]
like image 6
Ch3steR Avatar answered Oct 18 '22 18:10

Ch3steR