Open In App

Remove empty tuples from a list - Python

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of removing empty tuples from a list in Python involves filtering out tuples that contain no elements i.e empty. For example, given a list like [(1, 2), (), (3, 4), (), (5,)], the goal is to remove the empty tuples () and return a new list containing only non-empty tuples: [(1, 2), (3, 4), (5,)].

Using list comprehension

List comprehension is the most efficient way to remove empty tuples from a list. It creates a new list in a single line by filtering out empty tuples, making the code clear, concise, and fast.

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

res = [t for t in a if t]
print(res)

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

Explanation : list comprehension iterates over each element t in a, adding only non-empty tuples to res by filtering out those that evaluate to False.

Using filter()

filter() is a functional programming approach to remove empty tuples from a list. Using None as the first argument automatically filters out all falsy values, including empty tuples because empty tuples evaluate to False in Python.

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

res = list(filter(None, a))
print(res)

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

Explanation: list(filter(None, a)) filters out empty tuples from a by retaining only elements that evaluate to True, as empty tuples are False in Python.

Using itertools compress

compress() from the itertools module can remove empty tuples from a list by using a boolean mask. It creates a mask indicating whether each tuple is non-empty, and selects only the non-empty tuples based on the mask.

Python
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: list(compress(a, [bool(t) for t in a])) uses compress() with a boolean mask to filter out empty tuples from a, returning only non-empty tuples in res.

Using 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, but it’s less efficient compared to modern alternatives like list comprehension.

Python
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: for loop iterates over each tuple t in the list a, checks if t is non-empty evaluates to True and appends it to the list res.


Next Article
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy