[Edu-sig] how to make clear: understand references
Guido van Rossum
guido@python.org
Sun, 22 Sep 2002 23:42:54 -0400
> > If you focus all your examples on multi-dimensional arrays, yes, then
> > you'd need deep copying to be the default. But I think that is a
> > narrow-minded view on learning to program, based in the state of the
> > art in the early '60s (when arrays were the only data structuring
> > methodology available in programming languages).
>
> I did give two examples of multi-dimensional arrays, but the issue, I
> believe, is with the operators, not the arrays. I had suggested:
>
> >>> a = [[0] * 5].copy() * 3
>
> But, I now see that that doesn't fix the problem that I originally had,
> because, even a deepcopy doesn't help:
>
> >>> a = [deepcopy([0] * 6)] * 3 # or
> >>> a = deepcopy([[0] * 6]) * 3
> >>> a[0][0] = 4
> >>> a
> [[4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]
>
> So now we see that this particular confusion won't (easily) go away with
> anything other than understanding where to draw those little boxes
> around objects and understanding references.
Noticing that the problem is with the * operators is helpful. But it
is still a problem with lists because it is the list type's
multiplication operator. I really don't want the sequence * to make
copies of the items that are repeated; that would defeat the OO nature
of lists.
The solution is indeed to recognize that [[0]*m]*n is not the right
way to create an n*m array. You'll have to write a helper function,
e.g.:
def ndim(n, *args):
if not args:
return [0]*n
A = []
for i in range(n):
A.append(ndim(*args))
return A
--Guido van Rossum (home page: http://www.python.org/~guido/)