Open In App

Remove empty Lists from List – Python

Last Updated : 14 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will explore various method to remove empty lists from a list. The simplest method is by using a for loop.

Using for loop

In this method, Iterate through the list and check each item if it is empty or not. If the list is not empty then add it to the result list.

a = [[1, 2], [], [3, 4], [], [5]]
res = []

# Iterate over list 'a'
for b in a:
  
    # If list is not empty then add it to res.
    if b:
        res.append(b)

print(res)

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

Let’s explore other different methods to remove empty lists from a list:

Using list comprehension

We can also use list comprehension to filter empty list. This approach is similar to above method but this one is more concise.

a = [[1, 2], [], [3, 4], [], [5]]
res = [b for b in a if b]

print(res)

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

Explanation: [b for b in a if b] creates a new list and adding only non-empty list.

Using filter with lambda

We can use filter function with a lambda expression to remove empty list.

a = [[1, 2], [], [3, 4], [], [5]]

res = list(filter(lambda b: b, a))

# By using None as the first parameter in filter,
# it removes any falsy values (like empty list)

# res = list(filter(None, a)) # This will also work

print(res)

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

Explanation:

  • lambda b: b checks if each list is non-empty (evaluates to True) or empty (evaluates to False).
  • filter keeps only non-empty list since lambda returns True for them.
  • list() converts the filtered result to a list.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg