Reputation: 31
I have a list of tuples A
and list B
.
Here I want to delete tuples if the first element of tuples is in the list B
.
Here's the example:
A = [(0, 2), (1, 3), (2, 9), (3, 8)]
B = [1, 2]
wanted_list = [(0, 2), (3, 8)]
I coded like below but it didn't work
for i in A:
if i[0] in B:
A.remove(i)
print(A) # [(0, 2), (2, 9), (3, 8)]
What am I missing?
Upvotes: 0
Views: 55
Reputation: 1175
Use a list comprehension and check if the first element is present in B
A = [(0, 2), (1, 3), (2, 9), (3, 8)]
B = [1, 2]
C=[n for n in A if not n[0] in B]
print(C)
Upvotes: 1
Reputation: 486
You can make a new list and append the tuples whose first item is not in the list B.
A = [(0, 2), (1, 3), (2, 9), (3, 8)]
B = [1, 2]
lst = []
for i in A:
if i[0] not in B:
lst.append(i)
print(lst)
Upvotes: 0
Reputation:
Check this out.
C=[x for x in A if not any(b==x[0] for b in B)]
print(C)
Upvotes: 1
Reputation: 314
This should work:
wanted_list = [item for item in A if item[0] not in B]
Upvotes: 3