Compare recursively objects

Paul McGuire bogus at bogus.net
Wed Mar 17 16:30:27 CET 2004


"Nicolas Fleury" <nid_oizo at yahoo.com_remove_the_> wrote in message
news:LcZ5c.6697$kc2.157952 at nnrp1.uunet.ca...
> Hi everyone,
> Is there a way to compare recursively two objects (compare their
> members recursively)?  I'm only interested in equality or non-equality
> (no need for lower-than...).
>
> Thx and Regards,
> Nicolas
If you're comparing lists, here's an example (although list1==list2 also
works, see the verification in the test() function).  If you're comparing
something else, the logic is similar.

This example also does short-circuiting, in that it stops testing for
equality once the first mismatch is found.  Also, there is a slight
short-cut in isEqualElement, in comparison of two objects for equal identity
before testing for equal value.

-- Paul


def compareLists(lst1, lst2):

    def isEqualElement(e1,e2):
        print "Comparing",e1,"and",e2
        if e1 is e2:
            return True

        if type(e1) is type(e2):
            if isinstance(e1,list):
                return compareLists(e1,e2)
            else:
                return e1 == e2
        else:
            return False

    # or the same thing as a lambda, just remove '0' from name to
    # use the lambda instead
    isEqualElement0 = (lambda e1,e2:
        (e1 is e2) or
        ( ( type(e1) is type(e2) ) and
          ( ( isinstance(e1,list) and compareLists(e1,e2) ) or
          (e1 == e2) )
          )
        )

    if len(lst1) != len(lst2):
        return False

    for e1,e2 in zip(lst1,lst2):
        if not isEqualElement(e1,e2):
            return False

    return True


def test(lst1, lst2):
    print "Test:", lst1,"<->",lst2
    print compareLists(lst1,lst2)
    print lst1 == lst2
    print


test([1,2,3], [1,2,3])
test([1,2,3], [1,2])
test([1,'2',3], [1,2,3])
test([1,2,[3,4,5],6], [1,2,[3,4,5],6])
test([1,2,[3,4],6], [1,2,[3,4,5],6])
test([1,2,[7,4,5],6], [1,2,[3,4,5],6])





More information about the Python-list mailing list