0

hopefully somebody here can help me with this problem. I'm doing some revision for a 1st year programming exam on Friday and ran into something confusing me.

In my lecture slides discussing mutability, there is a particular part which doesn't work for me. The example is:

a = 'this is a string'
b = 'this is a string'
print(a is b)

False

But when I enter this in my program, it returns True instead. Also their ID's are identical. Now I would expect if I printed a == b it would return True, but surely a shouldn't be b as they are individual variables.

This was also a question from last years exam so would be helpful to understand this.

Any help on this matter much appreciated.

Jason Donavon
  • 73
  • 1
  • 1
  • 3
  • 1
    I think you are confusing the concepts of "variable" and "object". It [is guaranteed](https://docs.python.org/2/library/functions.html#id) that the id of an object is unique for its lifetime, so no other object can have it at the same time. But multiple identifiers can refer to the same object. That is what is happening with your `a` and `b` variables. – Kevin Jan 05 '16 at 17:58
  • Hi kevin, thanks for the response. I just don't understand how in the example from my lecture the exact same code displays `False`, while mine displays `True`. – Jason Donavon Jan 05 '16 at 18:26
  • The simple answer is because `id` and `is` have implementation-dependent behavior. Code executed by CPython may have a different result when executed by IronPython or Pypy, even though they're all strictly adhering to the same design document. The docs neither require nor forbid equal string literals to share space in memory, so it's basically a coin flip as to whether your code sample prints True or False. – Kevin Jan 05 '16 at 18:33

0 Answers0