Python Practice › Tuple Programs › Program 38

Remove empty tuples

EasyTuple Programs · 38 of 70

Write a Python program to remove empty tuples (and tuples holding only an empty string) from a list.

Advertisement
Input
[("",), ("a", "b"), ("a", "b", "c"), ("d",), ()]
Output
[('a', 'b'), ('a', 'b', 'c'), ('d',)]

Approach

  1. Keep tuples that contain at least one truthy value.

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs