1

Lets say I have a class

class Foo:
    def __init__(self, item1, item2):
        self.item1 = item1
        self.item2 = item2

And a objects list of that class

object1 = Foo (1,2)  
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]

I would like to know whether object2 with same items is in the list of objectlist and after that I would like to get the index of it. In this case 0 index.

I can do this by

def __eq__ (self, other):
    return (self.item1 == other.item1) and (self.item2 == other.item2)

And a for loop. Since I could be able to check every index one by one, and got the index if it equals to that object. But can I do it with more elagant way?

Meric Ozcan
  • 678
  • 5
  • 25

2 Answers2

3

How about?:

class Foo:
    def __init__(self, item1, item2):
        self.item1 = item1
        self.item2 = item2


    def __eq__ (self, other):
        return (self.item1 == other.item1) and (self.item2 == other.item2)

object1 = Foo (1,2)  
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]

try:
    index_value = objectlist.index(object2)
    print(index_value)
except ValueError:
    index_value = -1
    print(index_value)
Meric Ozcan
  • 678
  • 5
  • 25
LocoGris
  • 4,432
  • 3
  • 15
  • 30
0

The question is if you are going to differentiate between different objects but containing item1 and item2 of the same value.

If yes, then you do not have to check the contents of the object. Rather rely on the different identifier (id(obj)) of each instance of your class:

object2 in objectlist

If not, then your approach is (almost) the correct one and I am not aware of any better. In your case you are not strictly checking the class of both objects is the same rather - that they are structurally the same (i.e. they have the same members item1 and item2).

You may also want to review the answers of the following question: Compare object instances for equality by their attributes in Python

sophros
  • 14,672
  • 11
  • 46
  • 75