For mutable objects,
Lists, Dicts, Sets have a
Lists can also copied with:
To copy them together with the nested content,
copy.copy
and/or copy.deepcopy
can be used.Lists, Dicts, Sets have a
copy
method.Lists can also copied with:
import copy my_list_1 = [1, 2, 3] my_list_2 = my_list_1[:] my_list_3 = my_list_1.copy() my_list_4 = copy.copy(my_list_1)Lists can keep also lists and other objects.
To copy them together with the nested content,
copy.deepcopy
should be used.import copy nested_list_1 = [1, 2, [3, 4, 5], 6] nested_list_2 = nested_list_1[:] # the inner list is not copied nested_list_3 = copy.deepcopy(nested_list_1) # inner list is also copied nested_nested_list_1 = [[[1]], [[2]]] nested_nested_list_2 = copy.deepcopy(nested_nested_list_1) # now changing the 1 to 66 nested_nested_list_2[0][0][0] = 66 # nested_nested_list_1 has the original value 1 # nested_nested_list_2 has instead 66 print(nested_nested_list_1) print(nested_nested_list_2)Docs for copy module: https://docs.python.org/3/library/copy.html
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!