I found a strange behavior with the semicolon ";" in Python.
>>> x=20000;y=20000
>>> x is y
True
>>> x=20000
>>> y=20000
>>> x is y
False
>>> x=20000;
>>> y=20000
>>> x is y
False
Why does the first test return "True", and the others return "False"? My Python version is 3.6.5.
A semi-colon in Python denotes separation, rather than termination. It allows you to write multiple statements on the same line. This syntax also makes it legal to put a semicolon at the end of a single statement: print('Why God?
Python does not require semi-colons to terminate statements. Semicolons can be used to delimit statements if you wish to put multiple statements on the same line. A semicolon in Python denotes separation, rather than termination. It allows you to write multiple statements on the same line.
In the interactive interpreter, the first semi-colon line is read and evaluated in one pass. As such, the interpreter recognizes that 20000 is the same immutable int
value in each assignment, and so can (it doesn't have to, but does) make x
and y
references to the same object.
The important point is that this is simply an optimization that the interactive interpreter chooses to make; it's not something guaranteed by the language or some special property of the ;
that joins two statements into one.
In the following two examples, by the time y=20000
is read and evaluated, x=20000
(with or without the semi-colon) has already been evaluated and forgotten. Since 20000 isn't in the range (-5 to 257) of pre-allocated int
values, CPython doesn't try to find another instance of 20000 already in memory; it just creates a new one for 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