Is this a bug?

Chris Hoffmann (choffman@dvcorp.com)
Tue, 24 Jan 95 12:07:56 EST

Graham,
>> from time import clock
>> n = 100
>> m = 5
>> s1 = [ ["a"] * m ] * n
>> t = clock()
>> for i in range(n):
>> s1[i].append("a")
>> print len(s1), len(s1[1]), clock() - t

>>I get the output,

>> 100 105 0.099996
>> Is this a bug or am I missing something?

Yes, you're missing something :) Ironically, although the problem is
related to the multi-dimensional array discussion that's been going
on for a bit, I missed it too at first.

the line

>> s1 = [ ["a"] * m ] * n

doesn't create 100 COPIES of a 5-element list, but 100 REFERENCES to
the SAME 5-element list. Thus s1[i].append() is appending to the same
list each iteration. Try setting s1[0][0] to 'b' and then look at
s1[n][0] for any n. You'll see that it is also 'b'. Or,

>>> s1[0] is s1[1]
1

Chris

-- 
Chris Hoffmann				DataViews Corporation
choffman@dvcorp.com			47 Pleasant St. Northampton MA 01060
GCS d H s+: g+ ?p a w v+ C+$ US+ P++(++++) L E+(+++) N++ K W--->-- M+
V- po- Y+ t+ 5+(+++) Jx R G tv b+++ D+ B-() e+++ u++ h---- f r+++ n--- y++++