I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.
I thought I could simply do
for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both lists"
However this does not seem to work. Although if I do:
if item1.title == item2.title:
it works okay. I have more attributes than this though so don't really want to do 1 big if statement comparing all the attributes if I don't have to.
Can anyone give me help or advise on what I can do to find the objects which appear in both lists.
Thanks
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.
count() to check if the list contains. Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0. If it returns a positive integer greater than 0, it means the list contains the element.
The most straightforward way to check if an object is of type list is to use Python's built-in type() function that returns the type of the object passed into it. You can then use the equality operator to compare the resulting type of the object with the list using the expression type(object) == list . What is this?
Assuming that your object has only a title
attribute which is relevant for equality, you have to implement the __eq__
method as follows:
class YourObject: [...] def __eq__(self, other): return self.title == other.title
Of course if you have more attributes that are relevant for equality, you must include those as well. You might also consider implementing __ne__
and __cmp__
for consistent behaviour.
In case the objects are not the same instance, you need to implement the __eq__
method for python to be able to tell when 2 objects are actually equal.
Of course that most library types, such as strings and lists already have __eq__
implemented, which may be the reason comparing titles works for you (are they strings?).
For further information see the python documentation.
Here is a random example for __eq__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With