python assignment

Tim Peters tim.one at comcast.net
Sun Jul 27 18:25:35 EDT 2003


[dan]
> ...
> Can I always assume that an operation of this sort will return a new
> object, even if it has no effect on one of the operands?

Yup.  From the "Objects, values and types" section of the Language (not
Library) Reference Manual:

    ... for immutable types, operations that compute new values may
    actually return a reference to any existing object with the same
    type and value, while for mutable objects this is not allowed.
    E.g., after "a = 1; b = 1", a and b may or may not refer to the
    same object with the value one, depending on the implementation,
    but after "c = []; d = []", c and d are guaranteed to refer to
    two different, unique, newly created empty lists. (Note that
    "c = d = []" assigns the same object to both c and d.)

Other implications are that, e.g., if L is a list and T is a tuple, after

    L2 = L + []
    T2 = T + ()

"L2 is L" must be False, but "T2 is T" may be True or False.  There aren't a
lot of optimizations of the latter type in CPython today; most of them
involve strings, where an empty-string operand is quite common:

>>> s = "a string"
>>> t = s + ""
>>> id(s) == id(t)
True
>>> t = "" + s
>>> id(s) == id(t)
True
>>> t = ''.join([s])
>>> id(s) == id(t)
True
>>>






More information about the Python-list mailing list