Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python semicolon does make a difference

Tags:

python

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

But this same thing returns false.

>>> x = '123 4'
>>> y = '123 4'
>>> id(x) == id(y)
False

Same thing under function returns True

>>> 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
like image 308
Ankit Sachdeva Avatar asked Mar 05 '15 17:03

Ankit Sachdeva


1 Answers

>>> 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)).

like image 156
Joran Beasley Avatar answered Sep 19 '22 19:09

Joran Beasley