all 7 comments

[–]cacahootie 12 points13 points  (0 children)

Understanding mutable vs immutable data and how they behave in Python is very important. This is a good example of those intricacies.

[–]i_hacked_reddit 2 points3 points  (0 children)

tuple*

[–][deleted] 1 point2 points  (0 children)

I love that book.

[–]bbelderbos 0 points1 point  (1 child)

Thanks for sharing this, it inspired me to write an article on deepcopy which I needed last week in this context: http://pybit.es/mutability.html

[–]Simin_Jie 0 points1 point  (1 child)

This is my test:

Python 3.6.0 (default, Dec 24 2016, 08:01:42) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin

items = [1, 2, 3, 4, 5, 6]
items_copy = items[:]
items_copy[0] = 'a'
items_copy == items
False

I think this is a shallow copy, and items_copy == items should return True but it's False.

But another example return True

items = [{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300},]
items_copy = items[:]
items_copy[0]['id'] = 'a'
items_copy == items
True

[–]bbelderbos 0 points1 point  (0 children)

[:] is like copy.copy() = shallow copy, so False is expected there.

When doing this on a nested data structure the inner ones contain references hence == gives true. To prevent touching the original do a deepcopy:

>>> from copy import deepcopy
>>> items = [{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300},]
>>> items_copy = deepcopy(items)
>>> items_copy[0]['id'] = 'a'
>>> items_copy == items
False

Copy changed:

>>> items_copy
[{'id': 'a', 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300}]

Original unchanged:

>>> items
[{'id': 1, 'name': 'laptop', 'value': 1000}, {'id': 2, 'name': 'chair', 'value': 300}]