hichewness
hichewness

Reputation: 31

how to delete elements from this list of tuples

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

Answers (4)

AJITH
AJITH

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

Tanish Sarmah
Tanish Sarmah

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

user15801675
user15801675

Reputation:

Check this out.

C=[x for x in A if not any(b==x[0] for b in B)]
print(C)

Upvotes: 1

StrangeSorcerer
StrangeSorcerer

Reputation: 314

This should work:

wanted_list = [item for item in A if item[0] not in B]

Upvotes: 3

Related Questions