Python's Slicing Makes a Shallow Copy
Be mindful of your copies.
A slice object gets created as a result of an extended indexing syntax of lists e.g. a[1: 4]
. Those slice objects are shallow copies of the original list.
>>> a = [1, 2, 3, 4]
>>> b = a[1:3]
>>> b
[2, 3]
>>> a[1] = 'x'
>>> a
[1, 'x', 3, 4]
>>> b
[2, 3] # This is the proof of that b is not referencing the same data as a
>>> a = None
>>> b
[2, 3] # Additional proof.
>>> a = [1, {"a": "alpha", "b": "beta"}, 3, 4]
>>> b = a[1:3]
>>> a[1]["g"] = "gamma"
>>> a
[1, {'a': 'alpha', 'b': 'beta', 'g': 'gamma'}, 3, 4]
>>> b
[{'a': 'alpha', 'b': 'beta', 'g': 'gamma'}, 3]
So, here is the conclusion.
Appendix
If you copy the list, b
is referencing the same data as a
. This is, by the way, not called a shallow copy.
>>> a = [1, 2, 3, 4]
>>> b = a
>>> a[1] = 'x'
>>> a
[1, 'x', 3, 4]
>>> b
[1, 'x', 3, 4] # This is the proof that b is referencing a