Recommended first Watch video (youtube) Ned batchelder-facts and Myths about Python names and Values-pycon 2015
Change variable# rebindingx = x + # Mutatingnums.append (7)
# can also rebind lists:
Nums = Nums + [7]
# but you can ' t mutate immutable
Make a new list, and don ' t change the mutable param
def append_twice (a_list, val): a_list.append (val) a_list.append (val) def Append_twice_bad (a_list, val): "" This function is useless "" " a_list = a_list + [val, val]def append_twice_good (a_list, val): a_list = A_lis T + [val, val] return a_list
Shadowcopy and Deepcopy
The difference between shallow and deep copying are only relevant for compound objects (objects this contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent Possible) inserts references into it to the object s found in the Original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it's the objects found in the Ori Ginal.
Learn about compound Objects by image
# objects that contain other objects, like lists or class Instancesitems = [{' ID ': 1, ' name ': ' laptop ', ' value ': 1000}, {' ID ': 2, ' name ': ' Chair ', ' value ': 300},]
# but it's an int that doesn't belong to compound objects int question: doesn't it belong to object?
Items = [1, 2, 3]
Look at the difference between shadow copy and Deepcopy for compound object
From copy import deepcopy, copyitems = [{' ID ': 1, ' name ': ' laptop ', ' value ': +}, {' ID ': 2, ' name ': ' Chair ', ' value ': 30 0},]items_deep_copy = deepcopy (items) items_deep_copy[1][' id '] = ' b ' items_deep_copy = = itemsitems_copy = Copy (items) items_copy[1][' id '] = ' b ' items_copy = = items
As can be seen, deep_copy is all re-copied, and shadow copy only deep copy of the first layer, nested just copy the reference
Questions:
Items_copy = = items should return True but it ' s False.
# But another example return trueitems = [{' ID ': 1, ' name ': ' laptop ', ' value ': ' + ', ' id ': 2, ' name ': ' Chair ', ' value ': 300},]items_copy = items[:]items_copy[0][' id '] = ' a ' items_copy = = Itemstrue
Question: do all mutable objects is composed of immutable objects
[1, 2, 3] from 1, 2, 3
Like language is composed of words
python:names, values, Assignment and mutability