Wednesday, August 15, 2012

Python assigment, shallow copy, and deep copy

I 've copy many text from below links, but deleted them all. Never copy, never copy, never copy ^6^

Below links are MUST read, if you really use python

Must read, because you will write python code, not C/Java...
Code Like a Pythonista
Must read, to get to know about mutable and immutable object. Things seem not important to beginner but will cause many problems if you don't really understand it.
http://docs.python.org/reference/datamodel.html
Must read, because you must understand how does assigment, shallow and deep copy work.
http://docs.python.org/library/copy.html

If you dont, prepace to face many bug because lack of knowledge :)

"numbers, strings and tuples are immutable, while dictionaries and lists are mutable."


Every object has an identity (currently is implemented as its memory address), a type, and a value. To get id of each object, we use id(object). Let experience with list:

>>> li = [1, 2, 3]
>>> la = li
>>> id(li)
3073615404L
>>> id(la)
3073615404L
>>> li is la
True
>>> la
[1, 2, 3]
as you can see, assignment "la = li" just bind the name "la" to object that "li" binded to.

Now, let check int :
>>> a = 5
>>> b = a
>>> id(a)
155356512
>>> id(b)
155356512
>>> a = 7
>>> id(a)
155356488
>>> a
7
>>> b
5
>>> id(5)
155356512
>>> id(6)
155356500
>>> id(7)
155356488

after assigned "b = a", the name "b" is binded to object which name "a" is binded to. That object has id = 155356512, that is id of immutable object 5 (= id(5)).
Back to list again, now we will see how slice work (it will do a shallow copy)

>>> li = [1, 2, 3]
>>> id(li)
3073693068L
>>> la = li[:]
>>> id(la)
3073693292L
>>> li[0] = 0
>>> la
[1, 2, 3]
>>> li
[0, 2, 3]
"li" and "la" has different id, so when you change "li", "la" will not change. Objects that "li" and "la" contain are numbers(type int) and they are immutable objects. When you assign "li[0] = 0", you are binding the first element of list "li" to immutable object 0, you NOT change value of 1 to 0 (and you can't because it is immutable).

No comments: