Can't Understand Python Shallow Copy When Working With Int And Str
Solution 1:
As far as I know:Shallow copying means the content of the dictionary is not copied by value
, but creating a new reference.
Have a look at this example.
items = [{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300},]
items_copy = items[:]
items_copy[0]['id'] = 'a'print items_copy,id(items_copy),items,id(items)
print items_copy == items
Output:
[{'id': 'a', 'value': 1000, 'name': 'laptop'}, {'id': 2, 'value': 300, 'name': 'chair'}]4455943200[{'id': 'a', 'value': 1000, 'name': 'laptop'}, {'id': 2, 'value': 300, 'name': 'chair'}]4455866312
True
items = [{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300},]
items_copy = items[:]
items_copy[0]= 'a'print items_copy,id(items_copy),items,id(items)
print items_copy == items
Output:
['a', {'id': 2, 'value': 300, 'name': 'chair'}]4455943200[{'id': 'a', 'value': 1000, 'name': 'laptop'}, {'id': 2, 'value': 300, 'name': 'chair'}]4455866312
False
Solution 2:
This code:
items_copy[0] = 'a'
Means "replace the item in items_copy[0]
with a
. It changes the object referred to by items_copy
(and therefore changes all other variables that refer to that object, which in this case does not include items
), but has no effect at all on the item that was previously in items_copy[0]
(in this the dictionary).
This is similar to this sequence of events:
foo = {'id': 1, 'name': 'laptop', 'value': 1000}
bar = foo
foo = 'a'foo == bar
This would return False
, because bar
is still the (unchanged) dictionary object.
In the second case, you did not modify either list, but you did modify the (first) dictionary that is referred to by both copies, similar to this sequence:
foo = {'id': 1, 'name': 'laptop', 'value': 1000}
bar = foo
foo['id'] = 'a'
foo == bar
This would return True
. (This is slightly different from your second example because in this case foo
and bar
are not only equal but actually refer to the same object.)
Post a Comment for "Can't Understand Python Shallow Copy When Working With Int And Str"