10.11: Aliasing

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    10.11: Aliasing

    If a refers to an object and you assign b = a, then both variables refer to the same object:

    >>> a = [1, 2, 3]
    >>> b = a
    >>> b is a
    True
    

    The state diagram looks like Figure \(\PageIndex{1}\).

    State diagram.
    Figure \(\PageIndex{1}\): State diagram.

    The association of a variable with an object is called a reference. In this example, there are two references to the same object.

    An object with more than one reference has more than one name, so we say that the object is aliased.

    If the aliased object is mutable, changes made with one alias affect the other:

    >>> b[0] = 42
    >>> a
    [42, 2, 3]
    

    Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.

    For immutable objects like strings, aliasing is not as much of a problem. In this example:

    a = 'banana'
    b = 'banana'
    

    It almost never makes a difference whether a and b refer to the same string or not.


    This page titled 10.11: Aliasing was last modified on Tue, 01 Dec 2020 03:30:52 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.