Arash Howaida
Arash Howaida

Reputation: 2617

Remove Tuple if it Contains any Empty String Elements

There have been questions asked that are similar to what I'm after, but not quite, like Python 3: Removing an empty tuple from a list of tuples, but I'm still having trouble reading between the lines, so to speak.

Here is my data structure, a list of tuples containing strings

data
>>[
('1','1','2'),
('','1', '1'),
('2','1', '1'),
('1', '', '1')
]

What I want to do is if there is an empty string element within the tuple, remove the entire tuple from the list.

The closest I got was:

data2 = any(map(lambda x: x is not None, data))

I thought that would give me a list of trues' and falses' to see which ones to drop, but it just was a single bool. Feel free to scrap that approach if there is a better/easier way.

Upvotes: 4

Views: 2577

Answers (2)

Jens Astrup
Jens Astrup

Reputation: 2454

You can use filter - in the question you linked to None is where you put a function to filter results by. In your case:

list(filter(lambda t: '' not in t, data))

t ends up being each tuple in the list - so you filter to only results which do not have '' in them.

Upvotes: 6

Mahesh Karia
Mahesh Karia

Reputation: 2055

You can use list comprehension as follows:

data = [ ('1','1','2'), ('','1', '1'), ('2','1', '1'), ('1', '', '1') ]
data2 = [_ for _ in data if '' not in _]
print(data2)

output:

[('1', '1', '2'), ('2', '1', '1')]

Upvotes: 2

Related Questions