On Thu, Jun 17, 2010 at 4:20 PM, bart.c <ba...@freeuk.com> wrote: > > "J Kenneth King" <ja...@agentultra.com> wrote in message > news:87wrtxh0dq....@agentultra.com... >> >> candide <cand...@free.invalid> writes: >> >>> Let's the following code : >>> >>>>>> t=[[0]*2]*3 >>>>>> t >>> >>> [[0, 0], [0, 0], [0, 0]] >>>>>> >>>>>> t[0][0]=1 >>>>>> t >>> >>> [[1, 0], [1, 0], [1, 0]] >>> >>> Rather surprising, isn't it ? >> >> Not at all, actually. > > The code is clearly trying to set only t[0][0] to 1, not t[1][0] and t[2][0] > as well. > > This behaviour is quite scary actually, especially when t[0]=42 *does* work > as expected, while t[0][0]=42 is apparently duplicated. It appears > inconsistent. > >> I'd be surprised if the multiplication operator was aware of object >> constructors. Even arrays are "objects" in Python. Should the >> multiplication operator know how to instantiate three arrays from a >> single array instance? What about an instance of a user-defined class? > > Multiplication operators shouldn't need to be directly aware of any such > thing; it should just request that an object be duplicated without worrying > about how it's done. > > I don't know how Python does things, but an object should either specify a > special way of duplicating itself, or lend itself to some standard way of > doing so. (So for a list, it's just a question of copying the data in the > list, then recursively duplicating each new element..) > > -- > Bartc
It's the recursively duplicating each element that's the problem. How do you know when to stop? -- http://mail.python.org/mailman/listinfo/python-list