Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 681
longshuai ma Avatar asked Sep 13 '18 18:09

longshuai ma


People also ask

What happens when we use semicolon in Python?

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?

Does Python need semicolons?

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.


1 Answers

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.

like image 67
chepner Avatar answered Nov 10 '22 09:11

chepner