Python: How to remove empty lists from a list? [duplicate]
Try
list2 = [x for x in list1 if x != []]
If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use
list2 = [x for x in list1 if x]
You can use filter()
instead of a list comprehension:
list2 = filter(None, list1)
If None
is used as first argument to filter()
, it filters out every value in the given list, which is False
in a boolean context. This includes empty lists.
It might be slightly faster than the list comprehension, because it only executes a single function in Python, the rest is done in C.
Calling filter
with None
will filter out all falsey values from the list (which an empty list is)
list2 = filter(None, list1)