understanding list scope

alex23 wuwei23 at gmail.com
Sun Sep 21 09:16:32 EDT 2008


On Sep 21, 10:51 pm, Alex <metallourla... at gmail.com> wrote:
> Why? I'm coping data_set in ds so why data_set is changed?

You're making a copy of the ds tuple, which has the -same- contents as
the original. To create copies of the contents as well, try the
deepcopy function from the copy module.

As an aside, you're also trying to make a copy of ds for each
iteration of the loop, which is unnecessary in this case. Here's a
slightly better example of your code:

>>> from copy import deepcopy
>>> data_set = ({"param":"a"},{"param":"b"},{"param":"c"})
>>> ds = deepcopy(data_set)
>>> for i, data in enumerate(ds):
...     if i == 1: data['param'] = "y"
...     if i == 2: data['param'] = "x"
...
>>> print data_set
({'param': 'a'}, {'param': 'b'}, {'param': 'c'})
>>> print ds
({'param': 'a'}, {'param': 'y'}, {'param': 'x'})

Although your use of a tuple full of dicts for data_set is kinda
strange... Tuples are generally used when you want a structured data
element, in which case you'd just address each element directly rather
than iterate through it:

>>> ds = deepcopy(data_set)
>>> ds[1]['param'] = "y"
>>> ds[2]['param'] = "x"






More information about the Python-list mailing list