I know list is a kind of changeable collection of data object,but why the output is different. I thought they should be the same.
a = [1]
b = a
b = [1,2]
print(a)
output:
[1]
a = [1]
b = a
b.append(2)
print(a)
output:
[1,2]
In the first example you are overwriting:
a=[1]
b=a # b=[1] and b=a
b=[1,2] # b=[1,2] but not a
in the second example you apply a function built into lists:
a=[1]
b=a # b=[1] and b=a
b.append(1) # applies append to b which is a so a.append is done
a = [1]
b = a
b = [1,2]
print(a)
When you do this, the value for b
is reassigned therefore losing the connection with a
.
a = [1]
b = a
b.append(2)
print(a)
But here, appending to b
means the same list in the memory is appended a value. Since a
and b
still refer to the same memory, printing a
results the same as b
since they two are just two different aliases for the list.
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.