4

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.

Arash Howaida
  • 2,575
  • 2
  • 19
  • 50
  • If you can guarantee the only falsey elements in the tuples will be strings, you can get this down to `list(filter(all, data))` – Patrick Haugh Nov 22 '17 at 03:39

2 Answers2

6

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.

Jens Astrup
  • 2,415
  • 2
  • 14
  • 20
2

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')]
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23