[Edu-sig] Fw: Python sequences by reference - how to make clear

Douglas S. Blank dblank@brynmawr.edu
Fri, 20 Sep 2002 03:08:48 -0000


I'm not advocating anything, but provide the following only as data points on
common mistakes. 

Kirby makes some good points to consistency, but I'm not sure what would
change to help clear up the confusion that new users might have. For example,
here are two examples that seem to work initially, but then cause debugging
later to figure out what went wrong:

1. Creating multi-dimensional arrays of objects using the * operator:

>>> a = [0] * 5
>>> a[0] = 4
>>> a
[4, 0, 0, 0, 0]

works as expected, but:

>>> a = [[0] * 5] * 3
>>> a[0][0] = 4
>>> a
[[4, 0, 0, 0, 0], [4, 0, 0, 0, 0], [4, 0, 0, 0, 0]]

does not. 

2. And, of course, the assignment operator:

>>> a = [0] * 6
>>> b = a
>>> a[0] = 2
>>> b
[2, 0, 0, 0, 0, 0]

versus, 

>>> a = [0] * 6
>>> b = a[:]
>>> a[0] = 2
>>> b
[0, 0, 0, 0, 0, 0]

But, as Kirby mentioned, the [:] syntax only works with lists. A .copy()
method for all objects could be used on both examples above:

>>> a = [[0] * 5].copy() * 3

or even a newbie overgeneralized:

>>> a = [[0].copy() * 5].copy() * 3

and, for the other:

>>> b = a.copy()

I would assume that copy() would be a deepcopy by default (as that would be
what new users would assume). So, that might suggest a shallowcopy() method too.

-Doug

Kirby Urner <urnerk@qwest.net> said:

> 
> If copy and deepcopy *were* to be incorporated into the built-in domain,
> perhaps where they'd logically appear is as methods in the new base
> class (object).

[snip]

> 
> Kirby
> 
> 
> 
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
> 



-- 
Douglas S. Blank,       Assistant Professor         
dblank@brynmawr.edu,          (610)526-6501
Bryn Mawr College,  Computer Science Program
101 North Merion Ave,  Park Science Building
Bryn Mawr, PA 19010 dangermouse.brynmawr.edu