Explaining names vs variables in Python

Steven D'Aprano steve at pearwood.info
Wed Mar 2 05:16:38 EST 2016


On Wed, 2 Mar 2016 07:32 pm, Salvatore DI DIO wrote:

> Hello,
> 
> I know Python does not have variables, but names.
> Multiple names cant then be bound to the same objects.

Multiple names CAN be bound to the same object:

py> x = y = []
py> x is y
True
py> z = x
py> y.append("Hello world!")
py> z
['Hello world!']


So that is *three* names bound to the same list object.


> So this behavior
> 
>>>> b = 234
>>>> v = 234
>>>> b is v
> True
> 
> according to the above that is ok

When I try that in different versions of Python, I get different results:

# Python 2.4
py> b = 234
py> v = 234
py> b is v
False

What you are seeing is a version-dependent optimization. Not all versions of
Python will behave the same way. The reason you can do that is that
integers are immutable objects and cannot be modified. So the Python
interpreter will cache some integers, and avoid creating new objects. So:

py> a, b = 50, 9999
py> c, d = 50, 9999
py> a is c  # the same object is reused for 50 each time
True
py> c is d  # new int objects are created for 9999 each time
False


In Python 2.7, I think that the interpreter caches small ints from -1 to
255. But do not rely on this, because it is just an optimization and can
and will change from version to version.

You should never use `is` to test for equality. Use == to test for equality.
Use `is` *only* to test for object identity ("the same object").



-- 
Steven




More information about the Python-list mailing list