Reputation: 51
I have two lists and need to check if they contain the same objects in the same order.
list1 = [object1 , object2 , object3]
list2 = [object1 , object2 , object3]
list3 = [object2 , object3 , object1]
Comparing list list1
and list2
, result should be true
.
Comparing list list1
and list3
, result should be false
.
Edit: sample list example:list = [[<object1 at 0x04130AB0>], [<object2 at 0x04130210>, <object3 at 0x04130A10>]]
Upvotes: 1
Views: 6705
Reputation: 49310
A basic ==
will only check if each element in one list
is equal to the corresponding element in the other list
. However, given your example of lst = [[<object1 at 0x04130AB0>], [<object2 at 0x04130210>, <object3 at 0x04130A10>]]
, you are trying to check for identity. Two objects with different identities may compare as "equal," depending on that class's definition of that. Here are some examples where ==
would tell you that two list
s contain the same objects in the same order when they do not:
>>> import collections
>>> a = collections.Counter()
>>> b = collections.Counter()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> class Person:
... def __eq__(self, other):
... return True
...
>>> a = Person()
>>> b = Person()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> a = []
>>> b = []
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> l1 == l2
True
>>> a.append(0)
>>> l1 == l2
False
If you want to check that corresponding elements are actually the same object (identity, not equality), you will need to manually compare identities in some way, such as the following:
>>> import collections
>>> a = collections.Counter()
>>> b = collections.Counter()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
>>> a = Person()
>>> b = Person()
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
>>> a = []
>>> b = []
>>> a is b
False
>>> l1 = [a, b]
>>> l2 = [b, a]
>>> all(x is y for x,y in zip(l1, l2))
False
Upvotes: 2
Reputation: 12174
Assuming T's identity over equality distinction matters.
def check_id(li1, li2):
return [id(o) for o in li1] == [id(o) for o in li2]
Upvotes: 0
Reputation: 174716
Simple, Just use ==
to comapare two lists. This should return True
if two lists having same elements and should be placed in the same order else it returns False
list1 == list2
A function which implements the above logic should look like,
def check_lists(list1, list2):
return list1 == list2
Ex:
>>> ['object1' , 'object2' , 'object3'] == ['object1' , 'object2' , 'object3']
True
>>> ['object1' , 'object2' , 'object3'] == ['object3', 'object1' , 'object2' ]
False
>>> [['object1' , 'object2'] , ['object3']] == [['object1' , 'object2'] ,['object3']]
True
>>> [['object1' , 'object2'] , ['object3']] == [['object1' , 'object2'] , 'object3']
False
Upvotes: 2