Two-dimensional arrays

Steven Taschuk staschuk at telusplanet.net
Tue May 27 12:00:49 EDT 2003


Quoth Peter Slizik:
  [...]
> But I want to ask: When does Python merge two same objects into one and 
> when does it treat as two different objects? Is there any general rule?

"Merging" is not the right way to think of it.  Any time you
multiply a list you'll have multiple references to the same
objects.

    >>> L = ['foo bar']
    >>> L = 5*L
    >>> L
    ['foo bar', 'foo bar', 'foo bar', 'foo bar', 'foo bar']
    >>> L[0] is L[1]        # same object in both spots
    1

This list has five references to the same object.  Note that it is
possible (with this string, on CPython 2.2.2) to have a distinct
string object with the same characters:

    >>> x = 'foo bar'
    >>> L[0] is x           # distinct objects
    0
    >>> L[1] = x
    >>> L[0] is L[1]
    0

But multiplying a list doesn't create copies.  And *that's* the
way to think of it -- nothing's been merged, it's just that copies
haven't been made.

To put it another way: multiplying a list
    M = n*L
creates the same list as
    M = []
    for i in range(n):
        for elem in L:
            M.append(elem)
In this latter form I hope it is obvious that M gets multiple
copies of the same objects.

With lists of strings, ints, floats, etc., you won't usually
notice or care about this sharing, since these objects are
immutable; thus it doesn't matter whether you use one or many
objects for, e.g., the number 6.  But with mutable objects such as
lists...
    L = []
    M = 5*[L]
is equivalent to
    M = []
    for i in range(5):
        for elem in [L]:
            M.append(elem)
which could be simplified to
    M = []
    for i in range(5):
        M.append(L)
So you get five references to L, as before, and changes via any
one of them are visible via the others too.

-- 
Steven Taschuk             "[W]e must be very careful when we give advice
staschuk at telusplanet.net    to younger people: sometimes they follow it!"
                             -- "The Humble Programmer", Edsger Dijkstra





More information about the Python-list mailing list