Movatterモバイル変換


[0]ホーム

URL:


Open In App

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.

Python
a=[(1,2),(),(3,4),(),(5,)]res=[tfortinaift]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.

Python
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.

Python
fromitertoolsimportcompressa=[(1,2),(),(3,4),(),(5,)]res=list(compress(a,[bool(t)fortina]))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.

Python
a=[(1,2),(),(3,4),(),(5,)]res=[]fortina:ift: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.

Related Articles:


Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp