user1780424
user1780424

Reputation: 413

cannot remove a tuple from list of tuples using list comprehension

I have a list of tuples, and I want to remove an element from this list. I don't want to use the remove() method because the list is not unique and I want to remove all elements that match a given tuple.

So, why doesn't the code below remove the (21, 187) element?

edgeList = [(1, 2), (3, 75), (21, 187), (2, 6)]
edgeList = [(e1, e2) for e1, e2 in edgeList if (e1 != 21 & e2 != 187)]
print(edgeList)

The code above will print:

[(1, 2), (3, 75), (21, 187), (2, 6)]

Why is the tuple (21, 187) still there?

Upvotes: 1

Views: 254

Answers (3)

Igor Raush
Igor Raush

Reputation: 15240

Francisco's answer correctly points out that your problem arises because comparisons (e.g. !=) have lower precedence than bitwise boolean operators (e.g. &), but higher precedence than logical boolean operators (e.g. and). You could also avoid the issue entirely by doing something like

[e for e in edgeList if e != (21, 187)]

Tuples in python compare equal if all their elements compare equal.

Upvotes: 4

katelie
katelie

Reputation: 156

You can use & if you enclose each inequality check in parentheses: edgeList = [(e1,e2) for e1,e2 in edgeList if ((e1!=21) & (e2!=187))]

Upvotes: 1

Francisco
Francisco

Reputation: 11476

You're using the bit operator &, you want to use and:

edgeList = [(e1,e2) for e1,e2 in edgeList if (e1!=21 and e2!=187)]

The problem is that & has a different precedence than and, so you end up doing e1 != (21 & e2) != 187

Upvotes: 4

Related Questions