bcn
bcn

Reputation: 21

Why is this Python membership test not false?

Python 3.7: Why does

{'A'} not in {'A'}

evaluate to true?

Shouldn't the correct answer be 'false'? {'A'}.is

Following code does work for me:

not {'A'}.issubset({'A'})

But I'd like to understand why the first one won't.

Upvotes: 2

Views: 95

Answers (2)

ForceBru
ForceBru

Reputation: 44888

({'A'} not in {'A'}) is True
({'A'} in {'B', frozenset({'A'})}) is True
{'A'}.issubset({'A'}) is True
('A' not in {'A'}) is False

{'A'} doesn't literally contain the set {'A'}. It contains 'A'. {frozenset({'A'})}, however, does contain an inner set frozenset({'A'}) and a string 'B'. It's not possible to write {{'A'}} because that would require that the inner set be hashable, but sets are not hashable, while frozensets are.

Also {'A'} is a subset of itself, which is different from it literally containing a copy of itself.

Upvotes: 1

Victor
Victor

Reputation: 428

So, 'A' is a string, while {'A'} is a set, containing a string 'A'. Your right operand {'A'} does not contain your left operand {'A'} (it only contains 'A'), so the whole expression is true. But if you write 'A' not in {'A'}, the result would be False.

Upvotes: 0

Related Questions