Define a 2d Array?

skip at pobox.com skip at pobox.com
Sun Oct 12 18:43:58 EDT 2008


    Eric> I think you can do

    Eric> mylist = [[]] or somesuch...

That won't do what you want.  You've defined a list with a single element
(another list).  You might have been thinking of something like this:

    >>> N = 4
    >>> M = 5
    >>> mylist = [[0.0] * M] * N

While to the casual glance it looks like what you want:

    >>> print mylist
    [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]

assigning to an element of this structure demonstrates its shortcoming:


    >>> mylist[1][1] = 42.7
    >>> print mylist
    [[0.0, 42.700000000000003, 0.0, 0.0, 0.0], [0.0, 42.700000000000003, 0.0, 0.0, 0.0], [0.0, 42.700000000000003, 0.0, 0.0, 0.0], [0.0, 42.700000000000003, 0.0, 0.0, 0.0]]

There is just one copy of [0.0] * M referenced N times.

Skip



More information about the Python-list mailing list