Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python | Remove empty tuples from a list
When it is required to remove empty tuples from a list of tuples, Python provides several approaches. An empty tuple () evaluates to False in boolean context, making it easy to filter out.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuples basically contains tuples enclosed in a list.
Using List Comprehension
The most pythonic way is to use list comprehension with a boolean check ?
def remove_empty(my_tuple_list):
my_tuple_list = [t for t in my_tuple_list if t]
return my_tuple_list
my_tuple_list = [(), (), (''), (" " , " "), (45, 67, 35, 66, 74, 89, 100), 'jane']
print("The original list is:")
print(my_tuple_list)
print("Calling method to remove empty tuples...")
my_result = remove_empty(my_tuple_list)
print("The list after removing empty tuples is:")
print(my_result)
The original list is:
[(), (), (''), (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
Calling method to remove empty tuples...
The list after removing empty tuples is:
[(''), (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
Using filter() Function
The filter() function provides another clean approach ?
tuple_list = [(), (1, 2), (), (3,), (), ('a', 'b')]
print("Original list:", tuple_list)
# Using filter to remove empty tuples
filtered_list = list(filter(None, tuple_list))
print("After removing empty tuples:", filtered_list)
Original list: [(), (1, 2), (), (3,), (), ('a', 'b')]
After removing empty tuples: [(1, 2), (3,), ('a', 'b')]
Using a Simple Loop
For a more explicit approach, you can use a traditional loop ?
def remove_empty_loop(tuple_list):
result = []
for item in tuple_list:
if item: # Check if item is not empty
result.append(item)
return result
data = [(), (10, 20), (), ('hello',), ()]
print("Original:", data)
cleaned = remove_empty_loop(data)
print("Cleaned:", cleaned)
Original: [(), (10, 20), (), ('hello',), ()]
Cleaned: [(10, 20), ('hello',)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most Python code |
| filter() | Medium | Fast | Functional programming style |
| Loop | High | Slower | Complex filtering logic |
Explanation
- Empty tuples
()evaluate toFalsein boolean context - List comprehension
[t for t in list if t]keeps only truthy values - The
filter(None, list)removes all falsy values including empty tuples - Traditional loops provide more control but are more verbose
Conclusion
Use list comprehension for most cases as it's pythonic and efficient. The filter() function works well for functional programming approaches, while loops offer the most flexibility for complex filtering logic.
