1

Suppose I have this code:

a = [1,2]
b = [1,2]
def equivalentButDifferent(list1, list2):
    # list1 and list2 are lists
    return <is list1 and list2 the same or merely equivalent>

How do I return True for equivalentButDifferent(a,b) but False for equivalentButDifferent(a,a)?

2 Answers2

3

As @jonrsharpe said in the comment, this would be the function:

a = [1,2]
b = [1,2]
def equivalentButDifferent(list1, list2):
    return list1 == list2 and list1 is not list2
Enrico Agrusti
  • 507
  • 4
  • 15
1

The == or != operators compare the values for equity. In this case:

>>> a = [1,2]
>>> b = [1,2]
>>> a == b
True
>>> a != b
False

That is, a and b are equals.

is and not is compares the values for identity (if they are the same).

>>> a = [1,2]
>>> b = [1,2]
>>> c = a
>>> a is b
False
>>> a is c
True
  • Thanks!!! This actually helps me understand this distinction, which has been causing me some confusion in (what I thought were) a number of other areas too. I still think like a 90's C-engineer (pointers, etc), so my Google-fu didn't pick up on the previous question as I didn't realize that was the topic. – Weylin Piegorsch Sep 14 '22 at 13:24
  • 1
    Awesome! I'm glad I could help you. =) – julianofischer Sep 15 '22 at 15:40