I am aware of this answer (and of course the difference between the == and is operators! that is the point of the question!) but aren't a and b the same object also in the first case? (interpeter?) since they point to the same (immutable) string?

You'd have to check the cpython source code, but I'd imagine that the python interpreter is smart enough to realise that both those strings are the same and since strings are immutable its safe to point both variables to the same instance. Therefore an is check returns true. For the REPL as the strings are input incrementally there is no such optimization opportunity and both variables refer to different objects.
– Paul RooneyJan 24 '17 at 22:19

4

@AminEtesamian From what I understand, the question is rather on why the ids differs when using interpreter but are the same when running a .py file. I think pkaramol understands the difference between is and ==.
– HolyDannaJan 24 '17 at 22:20

I believe Paul is correct, when interpreting there is an opportunity for introspection and reuse, in the interpreter it just makes a new object instead.
– GRAYgoose124Jan 24 '17 at 22:21

So the console creates two different objects when creating two strings, but the interpreter, when running code in a single function will reuse the memory location of identical strings. Here is how to check if this is happening to you:

a = "my string"
b = "my string"
print id(a)
print id(b)

If these two ids are the same, then a is b will return True, if not then it will return False

Looks like you are using anaconda, so I checked this in the console and found different ids and then wrote a function in the editor and executed it and got the same ids.

Note: Now that we know that is determines if two variable labels point to the same object in memory, I should say that is should be used sparingly. It is usually used to compare singletons like None a is None, for example. So don't use it to compare objects, use ==, and when creating classes implement the __eq__ method so you can use the == operator.