2

Consider the following piece of code

    x=(1,2,3)
    y=(1,2,3)
    print(x is y)

When I run this code in the console, it gives back False.

When I run this code in a Python file, it gives back True.

Considering the Python Tutor and other sites, the result needs to be False. How is this possible? Does this have something to do with the way Python stores variables in the memory?

I'm using Python 3.8

CodeGuy
  • 19
  • 3
  • Highly unlikely that this really happens. just tried it with python3.7 and I get `False` both times. – Christian K. Apr 12 '20 at 11:23
  • @ChristianK. I can verify that in Python 3.7 you get `True` – John Coleman Apr 12 '20 at 11:26
  • @JohnColeman, wow, right! I accidently typed `python` instead of `python3`. You are right. – Christian K. Apr 12 '20 at 11:28
  • 2
    It is clearly some sort of optimization which is safe to do in view of the immutable nature of tuples. Python does the same thing with small integers – John Coleman Apr 12 '20 at 11:30
  • 1
    I'm also getting `True`. You can also verify that the addresses of the objects are actually identical with `id(x)` and `id(y)`. Didn't know that myself. But since `tuple` is actually immutable it makes sense that this is optimized. That might also explain why the Repl doesn't do this optimization. – BeneSim Apr 12 '20 at 11:31
  • Note that Python doesn't have variables (in the sense of names for fixed memory locations). There is only one object here, with two different names. – John Coleman Apr 12 '20 at 11:31
  • I checked with strings which are immutable as well. Shouldn't they behave the same? I get `True` in both cases. – Christian K. Apr 12 '20 at 11:33
  • @ChristianK. what you see with strings is Python [string interning](https://stackoverflow.com/q/15541404/4996248) in action. The shell, being a REPL, compiles statements as you enter them. When you have a file, it is able to do more of a whole-file optimization. – John Coleman Apr 12 '20 at 11:38
  • Is there any way to work around this? So that 2 tuples with the same value are different objects? – CodeGuy Apr 12 '20 at 11:59
  • 1
    @CodeGuy Well I guess you could just subclass `tuple`, so that you could produce two distinct objects. For me it seems to work ```python class MyTuple(tuple): pass x = MyTuple((1,2,3)) y = MyTuple((1,2,3)) print(x is y) ``` – BeneSim Apr 12 '20 at 12:27

1 Answers1

0

Apparently this is a problem in Python 3.8. I changed my interpreter to Python 3.6 and the code above now gives back False, like it should.

CodeGuy
  • 19
  • 3