Remove Empty Tuples from a List - Python
Given a list that contains both empty and non-empty tuples, the task is to remove all empty tuples from the list. For Example:
Input: [(1, 2), (), (3, 4), (), (5,)]
Output: [(1, 2), (3, 4), (5,)]
Let’s explore different methods to remove empty tuples from a list in Python.
Using List Comprehension
List comprehension provides a concise way to filter elements. It iterates through the list and includes only tuples that evaluate to True.
a = [(1, 2), (), (3, 4), (), (5,)]
res = [t for t in a if t]
print(res)
Output
[(1, 2), (3, 4), (5,)]
Explanation :
- if 't' filters out tuples that are empty because empty tuples evaluate to False.
- A new list is returned containing only non-empty tuples.
Using filter()
The filter() function removes elements that are falsy when the first argument is None.
a = [(1, 2), (), (3, 4), (), (5,)]
res = list(filter(None, a))
print(res)
Output
[(1, 2), (3, 4), (5,)]
Explanation:
- filter(None, a): keeps all elements that evaluate to True.
- Empty tuples are ignored since they are falsy in Python.
- Converting the result to a list gives the filtered output.
Using itertools.compress()
compress() allows filtering based on a boolean mask, which is constructed using the truth value of each tuple.
from itertools import compress
a = [(1, 2), (), (3, 4), (), (5,)]
res = list(compress(a, [bool(t) for t in a]))
print(res)
Output
[(1, 2), (3, 4), (5,)]
Explanation:
- bool(t): returns True for non-empty tuples, False for empty tuples.
- compress(a, mask): selects elements from a where the mask is True.
- The result is a new list with empty tuples removed.
Using a For Loop
This basic approach removes empty tuples from a list using a for loop and append(). It checks each tuple and appends only non-empty tuples to a new list.
a = [(1, 2), (), (3, 4), (), (5,)]
res = []
for t in a:
if t:
res.append(t)
print(res)
Output
[(1, 2), (3, 4), (5,)]
Explanation:
- Each tuple 't' is checked in a conditional if t.
- Non-empty tuples are appended to res.