Two-dimensional arrays
Anton Muhin
antonmuhin at sendmail.ru
Mon May 26 13:21:20 EDT 2003
Peter Slizik wrote:
>
> Hi pythoners,
>
> I'm working on a problem in which I have to use 2-dimensional array.
> I'm sorry, but I feel I should describe it precisely, so the question
> will be at the end of this mail.
>
> I created the 2-dim array using
>
> >>> dim = 5
> >>> array = [[0]*dim]*dim
>
> Here's how it looks like (using PrettyPrint):
>
> >>> pprint.pprint(array)
> [[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]]
>
> Then I tried to change some elements:
>
> >>> array[1][2] = 1
>
> The result looks quite strange:
>
> >>> pprint.pprint(array)
> [[0, 0, 1, 0, 0],
> [0, 0, 1, 0, 0],
> [0, 0, 1, 0, 0],
> [0, 0, 1, 0, 0],
> [0, 0, 1, 0, 0]]
>
> After a while of fooling around, I realised the problems is in
> references. The 2-dim array doesn't consist of five 1-dim arrays, but
> of five references to the same array.
>
> How can I overcome this problem? Or should I use some other approach to
> solve this 2-dim array problem - so trivial in C, but 'unsolvable' in
> Python?
>
> Thanx in advance
>
> Peter
>
And take look at Numeric module.
hth,
anton.
More information about the Python-list
mailing list