Palash Ahuja
Palash Ahuja

Reputation: 522

equating two sets in python

Suppose I have two lists a = [2,3,4] and b=[2,3,4] Then why

>>> set(a) in set(b)
False

although

>>> set(a) == set(b)
True

Upvotes: 0

Views: 2692

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

The set doesn't contain a set(2, 3, 4), it contains integers, 2, 3, and 4.

You could ask whether individual integers are in the set:

>>> 2 in set(b)
True

>>> 3 in set(b)
True

>>> 4 in set(b)
True

The documentation for set shows to check for containment you can do it two ways:

>>> set(a) <= set(b)
True

or

>>> set(a).issubset(set(b))
True

Upvotes: 2

heiparta
heiparta

Reputation: 11

Testing if one set contains another can be done with comparison operator or with .issuperset

>>> set([2, 3, 4]) >= set([2, 3])
True
>>> set([2, 3, 4]).issuperset(set([2, 3]))
True

See 8.7. sets — Unordered collections of unique elements

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You are testing if set(b) contains the literal set object. set(b) doesn't contain such an object.

If you want to test if set(a) is a subset or equal, use <=:

>>> set(a) <= set(b)
True

or use the set.issubset() method:

>>> set(a).issubset(b)
True

Either option also returns True for smaller sets where all elements are also contained in b:

>>> set([2, 3]) <= set(b)
True
>>> set([2, 3]).issubset(b)
True
>>> set([2, 3, 42]) <= set(b)
False
>>> set([2, 3, 42]).issubset(b)
False

Upvotes: 3

Related Questions