The Wayback Machine - https://web.archive.org/web/20241225115242/https://www.geeksforgeeks.org/python-remove-empty-tuples-list/
Open In App

Remove empty tuples from a list – Python

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

In this article, we will explore various method to remove empty tuples 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 tuple is not empty then add it to the result list.

Python
a = [(1, 2), (), (3, 4), (), (5,)]
res = []

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

print(res)

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

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

Using list comprehension

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

Python
a = [(1, 2), (), (3, 4), (), (5,)]
res = [t for t in a if t]

print(res)

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

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

Using filter with lambda

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

Python
a = [(1, 2), (), (3, 4), (), (5,)]

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

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

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

print(res)

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

Explanation:

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

Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg