Home > other >  determine if python lists are the same lists or merely equivalent lists
determine if python lists are the same lists or merely equivalent lists

Time:09-13

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)?

CodePudding user response:

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

CodePudding user response:

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
  • Related