1

Given a class, say

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

I would like to find the position in a list of an instance of this class. For instance, given

list = [1, 2, 3, Complex(1, 1)]

how can I find the position of Complex(1, 1)?

I tried list.index(Complex(1, 1)), but the object created from the second call to Complex is not the same as the first, so this results in a ValueError exception being raised.

How could I do this?

More generally, how could I find the position in a list of any instances of Complex (e.g. for list = [1, Complex(1, 1), 2, Complex(2, 2)] to return 1 and 3)?

  • 1
    You can use `isinstance(x, Complex)` as your condition, in place of the `xb`. – Aran-Fey Jan 17 '18 at 16:17
  • @Rawing Do you think it would be better that I remove the "More generally, ..." part of the post in order to not mark the question as duplicate? CoryKramer's answer and your comment point to `isinstance`, which was the important part that I was missing and that helped me. (See also my comment under CoryKramer's answer for what I had in mind about the "More generally, ..." part.) –  Jan 17 '18 at 17:05
  • It's not for me to say if you should rewrite your question. There's nothing wrong with your question being a duplicate, so you should ask your question as accurately as possible; there's no reason to try and avoid getting it marked as a dupe. And if the duplicate I found didn't accurately answer your question, we can probably find a better one. Or, if you don't think it's a duplicate, you should explain why. – Aran-Fey Jan 17 '18 at 17:13
  • @Rawing I see, then I will leave it as is. Thanks. –  Jan 17 '18 at 17:21

1 Answers1

1

You can define the __eq__ method for your class, which is what you'll use for any equality operators. This will allow list.index to work as you intended.

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
    def __eq__(self, other):
        if isinstance(other, Complex):
            return self.r == other.r and self.i == other.i
        else:
            return False

Example

>>> l = [1, 2, 3, Complex(1, 1)]
>>> l.index(Complex(1, 1))
3
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thanks CoryKramer. This also helps answering my more general question (I would replace `self.r == other.r ...` by `True`, and use, e.g., `Complex(_, _)` instead of `Complex(1, 1)`). –  Jan 17 '18 at 16:22