List assignment, unexpected result

Fernando Pérez fperez528 at yahoo.com
Mon Jul 8 17:05:47 EDT 2002


Steve Coates wrote:

> A friend of mine recently sent me some code and asked if I could
> predict what it would do. I guessed wrong. Code as follows:-
> 
> grid = [['.'] * 4 ] * 4
> grid [0][0] = '0'
> grid [1][1] = '1'
> grid [2][2] = '2'
> grid [3][3] = '3'
> for i in grid: print i

If this will be done for large grids, I suspect you're better off using 
Numeric arrays for it. You can later always write a special print method 
which gives you the '.' output as needed:

In [2]: diagonal_matrix (arange(5))
Out[2]:
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 2, 0, 0],
       [0, 0, 0, 3, 0],
       [0, 0, 0, 0, 4]])

In [3]: @psource diagonal_matrix
def diagonal_matrix(diag):
    """Return square diagonal matrix whose non-zero elements are given by the
    input array."""

    return diag*identity(len(diag))

Cheers,

f.



More information about the Python-list mailing list