b = [0]
def copyalist(b):
b = [1, 2, 3]
print(b)
copyalist(b)
print(b)
The outputs are below:
[1, 2, 3]
[0]
The first line indicates that in the function, b was set to [1, 2, 3]; However, when you print(b) out of the function,the second output says that b is still [0].
I don't understand that, why the outer b is not changed?
I also tried b = copy.deepcopy([1, 2, 3]), the outputs are the same.
However, the following code works well:
b = [0]
def copyalist(b):
b += [1, 2, 3]
print(b)
copyalist(b)
print(b)
The outputs are below:
[0, 1, 2, 3]
[0, 1, 2, 3]
In python, lists are passed as function arguments only by reference, ie, only the memory address of the first element is given. When defining a new b
inside the function, you just change the position in memory to which the inner variable b
refers, but the outer b
still points to the original position. Vice versa, when you do b += [1, 2, 3]
, you change the content inside the cell referenced by the inner b
and, since inner and outer b
point to the same cells, it reflects in a change of the outer b
as well.
b = copyalist(b)
and return b in the function
def copyalist(b):
b = [1, 2, 3]
return(b)
When you are defining something in a function it is only used inside that function.
This code:
def copyalist(b):
b = [1, 2, 3]
print(b)
will only mean to remap the variable name b
to a new list, but not modifying the original b
. If you mean to modify the original list, you have to explicitly tell Python to replace the actual content. The way to do is:
def copyalist(b):
b[:] = [1, 2, 3]
print(b)
This is due to a difference in global and local variables. You can add global to your function to get the desired result.
b = [0]
def copyalist():
global b
b = [1, 2, 3]
print(b)
copyalist()
print(b)
OUTPUT
[1, 2, 3]
[1, 2, 3]
A more in depth summary is here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.