Have a look at the copy module if you have a somewhat "complex" object graph to duplicate. Remember, you're essentially just creating another reference to a singular list object with simple assignment (a = b).
>>> a = [1,2,3,4, ['5a', '5b', '5c', ['6a', '6b','6c']], 7,8] >>> b = a >>> a [1, 2, 3, 4, ['5a', '5b', '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = None >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> import copy >>> d = copy.deepcopy(a) >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> a[4][1] = "Something" >>> a [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> b [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] >>> d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] >>> Thanks, Jeff On 1/24/08, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > I have run into a bit of a subtle problem. How do I go about > duplicating a variable (particularly a list of lists) in python. I > was surprised when simple assignment didn't work. For example, let y = > [1,2,3] > > >>> x = y > >>> x[2] = 5 > >>> y > [1,2,5] > > It seems that simply assigning x to y allows further modification of y > via x. (I'm new to python and I'm sure this is obvious to experienced > users). So my question, how do I go about duplicating a variable > which I can then manipulate independently? > > Thanks, > > -Hans > -- > http://mail.python.org/mailman/listinfo/python-list >
-- http://mail.python.org/mailman/listinfo/python-list