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
Remove Tuples from the List having every element as None in Python
When working with lists of tuples, you may need to remove tuples where every element is None. This is different from removing tuples that contain any None values. Python provides several approaches to filter out tuples containing only None elements.
Using List Comprehension with all()
The most efficient approach uses list comprehension with the all() function to check if every element in a tuple is None ?
my_list = [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None, ), (None, 45, 6)]
print("The list is :")
print(my_list)
my_result = [sub for sub in my_list if not all(elem is None for elem in sub)]
print("The None tuples have been removed, the result is :")
print(my_result)
Output
The list is : [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None,), (None, 45, 6)] The None tuples have been removed, the result is : [(2, None, 12), (23, 64), (121, 13), (None, 45, 6)]
Using filter() Function
You can also use the filter() function with a lambda expression ?
my_list = [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None, ), (None, 45, 6)]
my_result = list(filter(lambda sub: not all(elem is None for elem in sub), my_list))
print("Filtered result:")
print(my_result)
Filtered result: [(2, None, 12), (23, 64), (121, 13), (None, 45, 6)]
How It Works
The
all()function returnsTrueif all elements in an iterable are truthy (or the iterable is empty)all(elem is None for elem in sub)checks if every element in the tuple equalsNoneThe
notoperator reverses this condition to keep tuples that have at least one non-NoneelementUsing
is Noneinstead of== Noneis the recommended Python practice forNonecomparisons
Key Points
This method only removes tuples where every element is
NoneTuples with mixed
Noneand non-Nonevalues are preservedEmpty tuples
()would be preserved sinceall()returnsTruefor empty iterables
Conclusion
Use list comprehension with all() to remove tuples containing only None elements. The filter() approach works similarly but list comprehension is generally more readable and Pythonic.
