-2

I am trying to compare two sets

#logical operators

set1 = {1,2,3,4,5,6}

set2 = {1,2,3,4,5,6,7}

# is operator
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)

This result is as expected "False"

set2.remove(7)
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)

Question : I was expecting the output of this one should be "True", but i see its "False" , When I print two sets i see exactly same. Please let me know if i am missing something here on sets.

set3 = set1

is_set1_set3_same =  set1 is set3

print(is_set1_set3_same)

This results as expected "True"

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Aru
  • 1

1 Answers1

1

is is not a set operator - it is an operator for object references.

set3 = set1 will be making the set3 object reference the same as object set1, therefore is will be True always, regardless of the type of object.


To compare set equality, you must check if they are proper subsets of one another

sets_same = (set1 <= set2) and (set2 <= set1)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245