Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created August 17, 2017 19:03
Show Gist options
  • Save theY4Kman/da91d297cb27bb5e041702694b837fef to your computer and use it in GitHub Desktop.
Save theY4Kman/da91d297cb27bb5e041702694b837fef to your computer and use it in GitHub Desktop.
A demonstration of `copy.deepcopy` directly copying certain immutable types, instead of creating copies. This is in contrast to a literal copy-paste of the list, which will instantiate new PyObjects for ints outside the 0-256 range.
import copy
x = [257, 258, 259]
y = copy.deepcopy(x)
z = [257, 258, 259]
header = [('', 'x', 'deepcopy(x)', 'z')]
rows = [(i, id(i), id(j), id(k)) for i, j, k, in zip(x, y, z)]
for cols in header + rows:
print '%10s%14s%14s%14s' % cols
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>>
>>> x = [257, 258, 259]
>>> y = copy.deepcopy(x)
>>> z = [257, 258, 259]
>>>
>>> header = [('', 'x', 'deepcopy(x)', 'z')]
>>> rows = [(i, id(i), id(j), id(k)) for i, j, k, in zip(x, y, z)]
>>>
>>> for cols in header + rows:
... print '%10s%14s%14s%14s' % cols
...
x deepcopy(x) z
257 15592584 15592584 15592440
258 15592560 15592560 15592416
259 15592608 15592608 15592656
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment