阅读本文大约需要2分钟
Python code shows as follows:
What will happen after the operation ?
A、list1 = (1,[2,3,6,7],(4,5));
B、Error
C、Both
Think for a while, and the right answer is C.
But why?
Dissemble the program and you will know the process.
STEP 1: get the list (list1[1])
STEP 2: revise the list in-place
STEP 3: return the new tuple element into object
STEP 4: for tuple is an immutable object, a Type Error is thus triggered
However, its member (list1[1]) has already modified
We can examine the explanation by id()
The similar trick also applies to copy.
Function parameters should also be carefully used.
Summary:
For mutable objects, changes happen in-place (with the same id)
eg,list
For immutable objects, create, initialize and then set value (id changes)
eg,number, tuple
往期文章
联系我
领取专属 10元无门槛券
私享最新 技术干货