python clone object code example

Example 1: python clone object

import copy

new_ob = copy.deepcopy(old_ob)

Example 2: python deepcopy

>>> import copy
>>> nums = [1, 2, 3]
>>> data = {'a': 10, 'b': nums}
>>> data
{'a': 10, 'b': [1, 2, 3]}
>>> data_copy = copy.copy(data)
>>> data_deep = copy.deepcopy(data)
>>> data_copy
{'a': 10, 'b': [1, 2, 3]}
>>> data_deep
{'a': 10, 'b': [1, 2, 3]}
>>> data_copy['a'] += 2
>>> nums[1:1] = [254]
>>> data
{'a': 10, 'b': [1, 254, 2, 3]}
>>> data_copy
{'a': 12, 'b': [1, 254, 2, 3]}
>>> data_deep
{'a': 10, 'b': [1, 2, 3]}

Example 3: python copy variable

>>> import copy
>>> a = 0
>>> b = 2
>>> a = copy.copy(b)
>>> b += 1
>>> a
2
>>> b
3

Example 4: .copy python

new_list = list.copy()

# returns a new list without modifying the orginal list.

Tags:

Misc Example