I have two lists of tuples.
The first list has tuples with two elements:
list_a = [('a','apple'), ('b','banana'), ('c','cherry')]
A second list has tuples with only one element:
list_b = [('d',), ('e',), ('a',)]
I need to remove tuples in list_a for which the first element of the tuple is included in list_b. So the goal is that list_a is rendered:
list_a = [('b','banana'), ('c','cherry')]
I’ve tried:
for la in list_a:
if la[0] in list_b:
list_a.remove(la)
You can’t remove elements from a list you are looping over. Use a list comprehension instead:
Note that we test for
la[:1]to test with a (single element) tuple;la[0]is just the single character string.If you have to do this very often, consider using a set for
list_binstead:Lookups in a set take constant time, vs. linear time for a list membership test.