0


One of my friend asked me, why when he uses list(set(False, 0, True, 1)), he gets [0, 1]? I explained him that bool is subclass of int and bool doesn't redefinned __eq__ method of int object.
I go deeper for the exemple and I redefinned __eq__ method of int object, here is the code:

class AnotherInt(int):
    def __eq__(self, other):
        return (type(other) is int and super(AnotherInt, self).__eq__(other))
    __hash__ = int.__hash__

The thing is I get unordered elements (I mean, not the same order as the source) after executing some instructions. Here are the code:

mylist = [AnotherInt(0), False, False, AnotherInt(1), True, True, AnotherInt(2), 2, AnotherInt(3), 3, AnotherInt(4)]
# mylist : [0, False, False, 1, True, True, 2, 2, 3, 3, 4]
list(set(mylist))
# result : [0, False, 2, 1, True, 3, 4]

I got that result instead of [0, False, 1, True, 2, 3, 4]
is someone can explain me why?
PS: I use python 3.6.9; gcc 8.3.0

m0r7y
  • 670
  • 1
  • 8
  • 27
  • 3
    Sets are unordered, like dictionaries. So turning a list into a set, then back to a list will introduce the possibility of the items being in a different order – schwartz721 Feb 02 '20 at 06:11
  • @schwartz721, but when I don't use AnotherInt, i always get ordered list (as the source list) when I use set. – m0r7y Feb 02 '20 at 06:14
  • @schwartz721, my question is duplicated. Thank you for your answer. – m0r7y Feb 02 '20 at 06:17

0 Answers0