I want to compare two lists of tuples:
larry = [(1,'a'), (2, 'b')]
moe = [(2, 'b'), (1, 'a')]
such that the order of the items in the list may differ. Are there library functions to do this ?
>> deep_equals(larry, moe)
True
If I understand you, your tuples represent sets, and your lists represent sets. The obvious thing to do is to convert them to sets:
def setterific(l):
return frozenset(frozenset(p) for p in l)
setterific(larry) == setterific(moe)
This uses frozensets, because one cannot have sets of sets in python (because sets are mutable); see How can I create a Set of Sets in Python?.
If you only have one level of sets, go with frozenset(larry) == frozenset(moe)
.
If all you care about is the order of the items in the outermost list (which is what all except the word "deep" suggests to me—it alone brings doubt into my mind as to what you meant), and you know that there are going to be no duplicates, you can use a set
.
>>> larry = [(1,'a'), (2, 'b')]
>>> moe = [(2, 'b'), (1, 'a')]
>>> set(larry) == set(moe)
True
If the case is as simple as these two-tuples, you could also use a dict
, which would be {1: 'a', 2: 'b'}
. This may or may not be a more convenient structure for you. The comparison of dict(larry) == dict(moe)
will do what you want, anyway.
If you care about duplicates, it will take a bit more work, taking copies of the lists and pulling out items one by one until it fails or one is empty.