When in a Python interactive session:
In [1]: a = "my string"
In [2]: b = "my string"
In [3]: a == b
Out[3]: True
In [4]: a is b
Out[4]: False
In [5]: import sys
In [6]: print(sys.version)
3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609]
On the other hand, when running the following program:
#!/usr/bin/env python
import sys
def test():
a = "my string"
b = "my string"
print(a == b)
print(a is b)
if __name__ == "__main__":
test()
print(sys.version)
The output is:
True
True
3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609]
Why a is b
has different outcome in the above two cases?
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?