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.
Must read, because you must understand how does assigment, shallow and deep copy work.
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
>>> li is la
>>> laas you can see, assignment "la = li" just bind the name "la" to object that "li" binded to.
[1, 2, 3]
Now, let check int :
>>> a = 5
>>> b = a
>>> a = 7
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]"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", 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).
>>> la = li[:]
>>> li = 0
[1, 2, 3]
[0, 2, 3]
Post a Comment