0

I am confused on why the first code snippet in the code below evaluates to false, and the second to true:

print(frozenset((1, 2, 3)) is frozenset((1, 2, 3)))
print((1, 2, 3) is (1, 2, 3))
  • 3
    Why do you think *either* should evaluate to `True`? What exactly are you asking? The behavior of identity here is going to be dependent on implementation details. – juanpa.arrivillaga Jun 07 '20 at 11:14
  • Here a very good explanation, https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is – sushanth Jun 07 '20 at 11:15
  • 1
    It's probably an interpreter-specific optimisation, you shouldn't rely on identity comparison there. – jonrsharpe Jun 07 '20 at 11:15
  • @juanpa.arrivillaga I think both should evaluate to False, as in both cases I believe we are creating a new object. I just asked why it evaluates to True in the second example. –  Jun 07 '20 at 11:17
  • Tuples and frozensets are both immutable, so the interpreter *could* keep some kind of lookup and reuse the exact same object every time the same values are contained. What you're seeing is that the interpreter you're using does so for the tuple but not the frozenset. Even then there might be limits around that, e.g. maybe only short tuples are treated that way. – jonrsharpe Jun 07 '20 at 11:21
  • Why doesn't it do it for frozensets though? BTW, I tried doing ```tuple([1, 2, 3]) is tuple([1, 2, 3])```, which returned False, so I guess it has to do with the constructor that the first example evaluated to False –  Jun 07 '20 at 11:23
  • @NB575 ok, it's good to make that clear. Suffice it to say, the python interpreter and runtime is free to optimize the actual creation of distinct objects when those objects are immutable. – juanpa.arrivillaga Jun 07 '20 at 11:25
  • You'd have to ask the maintainers of the implementation. Maybe it's a different cost-benefit trade off, e.g. for a more or less frequent use, maybe they just didn't get around to it yet. – jonrsharpe Jun 07 '20 at 11:25
  • 1
    See e.g. https://stackoverflow.com/a/25368371/3001761 for discussion of some optimisations around tuples and frozensets in CPython. – jonrsharpe Jun 07 '20 at 11:26

0 Answers0