Why does adding a semicolon in Python change the result? [duplicate]

  • A+
Category:Languages

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.

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: