Python Practice › Tuple Programs › Program 38
Remove empty tuples
Write a Python program to remove empty tuples (and tuples holding only an empty string) from a list.
Input
[("",), ("a", "b"), ("a", "b", "c"), ("d",), ()]Output
[('a', 'b'), ('a', 'b', 'c'), ('d',)]Approach
- Keep tuples that contain at least one truthy value.
Solution
data = [("",), ("a", "b"), ("a", "b", "c"), ("d",), ()]print([t for t in data if any(t)])Output
[('a', 'b'), ('a', 'b', 'c'), ('d',)]Line by line
Line 2
any(()) is False and any(("",)) is False, so both are removed.
Learn the concept
New to this topic? Read the lesson, then come back.