On Wed, 10 Aug 2005 12:40:54 +0200, Jiri Barton <[EMAIL PROTECTED]> wrote: >Hi everyone, > >I have a problem with initialization. >>>> a, b = [[]]*2 >>>> a.append(1) >>>> b >[1] > >Why is this? Why does not this behave like the below: > >>>> a, b = [[], []] >>>> a.append(1) >>>> b >[]
In your 1st example a and b point to copies of the same object, in the second example the point to two separate objects that happen to have the same repr() representation. Here's another example of the same thing: >>> c = [] >>> d = [c,c] >>> e = [[],[]] >>> d [[], []] >>> e [[], []] (d) and (e) appear to be the same (i.e. they have the same repr() form), but they are not. Consider: >>> e[1].append("spam") >>> e [[], ['spam']] But: >>> d[1].append("spam") >>> d [['spam'], ['spam']] The point is that in Python an object's repr() -- which stands for "representation" -- doesn't actually tell you how the object is represented inside the innards to the Python system. Incidently I am currently working on a programming language that fixes this problem. In my language "Unify", the equivalent of repr is called "storage manager format" (or SM-format) because if two values have the same SM-format it is guaranteed that the system will treat them identiacally. The SM-format can thus be used for serialisation, and incidently it is also the same format in which literals are written in a program. In Unify to specify an Array containing two separate empty Arrays would look like this: e := #(() ()) The code to add a value to one sub-array, and print the result is: e[1] @= 'spam'. // means same as Python d[1].append("spam") out << sm(e). // convert to SM-string, output it to stdout This would print this text: #(() (spam)) An array containing two copies of the same sub-array might look like this: d := #( () &[0] ) Where "&[0]" means "pointer to the 0th array subscript". -- Email: zen19725 at zen dot co dot uk -- http://mail.python.org/mailman/listinfo/python-list