Why does use of a colon make difference to the result? And what should be the correct result?
# Not stored in a different location.
>>> id('123 4')== id('123 4')
True
# Also returns true
>>> x = '123 4'; y ='123 4'; id(x) == id(y)
True
>>> x = '123 4'
>>> y = '123 4'
>>> id(x) == id(y)
False
>>> def test():
... x = '123 4';y='123 4'; print (id(x)==id(y))
... a = '123 4'
... b='123 4'
... print (id(a)==id(b))
...
>>> test()
True
True
>>> x="123 4";y="123 4"
Python is smart enough to recognize both variables get the same value (since they are interpreted in the same line) and so stores that value in the same memory location (that is, id(x) == id(y)
).
However
>>> x="123 4"
>>> y="123 4"
Python is not smart enough to realize they are both the same value (since they are interpreted on separate lines) and so stores each in its own memory location (that is, id(x) != id(y)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With