Python, why you always lying?
Question:
Python seems to be inconsistent.
x = 100
y = 100
x is y
Returns True, yet:
x = 300
y = 300
x is y
Returns False.
I even tried with new, clean variables:
> x = 100
> y = 100
> x is y
True
> x = 300
> y = 300
> x is y
False
> x = 100
> y = 100
> x is y
True
> x2 = 300
> y2 = 300
> x2 is y2
False
> x2
300
> y2
300
> x2 is y2
False
> x2 = 100
> y2 = 100
> x2 is y2
True
What is happening here? Am I confused about the "is" key word?
Answers:
The is
keyword compares whether two things are actually the same object. An easy way to think about this is in terms of memory addresses – that is, x is y
is another way of writing id(x) == id(y)
There is no guarantee that two objects assigned to the same value will share the same memory address. Sometimes they will, though. That’s all that’s going on.
If you wish to compare the variables’ values, use the comparison operator:
x == y
Edit: upon doing some research, it seems that python uses the same memory adresses for integers in the range [-5, 256]
(this is pretty arbitrary, but there is some reasoning for it: it’s just some common negative numbers along with 0 – 255, plus 256 because it’s also a common number). That would explain why is
returns True
for 100 but not 300.
So, 256 is 256
returns True
, but 257 is 257
returns False
Python seems to be inconsistent.
x = 100
y = 100
x is y
Returns True, yet:
x = 300
y = 300
x is y
Returns False.
I even tried with new, clean variables:
> x = 100
> y = 100
> x is y
True
> x = 300
> y = 300
> x is y
False
> x = 100
> y = 100
> x is y
True
> x2 = 300
> y2 = 300
> x2 is y2
False
> x2
300
> y2
300
> x2 is y2
False
> x2 = 100
> y2 = 100
> x2 is y2
True
What is happening here? Am I confused about the "is" key word?
The is
keyword compares whether two things are actually the same object. An easy way to think about this is in terms of memory addresses – that is, x is y
is another way of writing id(x) == id(y)
There is no guarantee that two objects assigned to the same value will share the same memory address. Sometimes they will, though. That’s all that’s going on.
If you wish to compare the variables’ values, use the comparison operator:
x == y
Edit: upon doing some research, it seems that python uses the same memory adresses for integers in the range [-5, 256]
(this is pretty arbitrary, but there is some reasoning for it: it’s just some common negative numbers along with 0 – 255, plus 256 because it’s also a common number). That would explain why is
returns True
for 100 but not 300.
So, 256 is 256
returns True
, but 257 is 257
returns False