python - When is a reference created, and when is a new memory block allocated and then copy? -
>>> d {1: 1, 2: 2, 3: 3} >>> lst = [d, d] >>> c=lst[0] >>> c[1]=5 >>> lst [{1: 5, 2: 2, 3: 3}, {1: 5, 2: 2, 3: 3}]
when lst = [d, d]
, lst[0]
, lsg[1]
both references memory block of d
, instead of creating 2 memory blocks , copy content of d
them respectively?
when c=lst[0]
, c
reference memory occupied lst[0]
, instead of creating new memory block , copy content lst[0]
?
in python, when reference created point existing memory block, , when new memory block allocated , copy?
this language feature of python different c. name of language feature?
thanks.
all variables (and other containers, such dictionaries, lists, , object attributes) hold references objects. memory allocation occurs when object instantiated. simple assignment creates reference existing object. example, if have:
a = [1, 2, 3] b =
then b
, a
point same object, list. can verify using is
operator:
print(b a) # true
if change a
, b
changes too, because 2 names same object.
a.append(4) print(b[3] == 4) # true print(b[3] a[3]) # true
if want create copy, must explicitly. here ways of doing this:
- for lists, use slice:
b = a[:]
. - for many types, can use type name copy existing object of type:
b = list(a)
. when creating own classes, approach take if need copy functionality. - the
copy
module has methods can used copy objects (either shallowly or deeply).
for immutable types, such strings, numbers, , tuples, there never need make copy. can "change" these kinds of values referencing different ones.
the best way of describing "everything's object." in c, "primitive" types integers treated differently arrays. in python, not: values stored references objects—even integers.
Comments
Post a Comment