Give * operator "deep copy"

Nick Jacobson nicksjacobson at yahoo.com
Tue Aug 31 21:54:05 CEST 2004


This question is with regard to the * operator as used for sequence
concatenation.

There's the well-known gotcha:

a = [[1, 2]]
b = a*3
b[0][0] = 4
print b


Result:
[[4, 2], [4, 2], [4, 2]]

When you wanted:
[[4, 2], [1, 2], [1, 2]]

My question is, since b = a*3 is equivalent to b = a + a + a, why not
use deep copies of a?  That is, let b = a*3 be equivalent to:

b = copy.deepcopy(a) + copy.deepcopy(a) + copy.deepcopy(a)

It seems much more likely that someone would want to create copies of
an item, rather than inserting the same item several times into the
list.


If this has been previously discussed/documented, please point me to
where I can read about it.

Thanks!

--Nick



More information about the Python-list mailing list