0
Why does append update each list that is equal to the list that it operates?
See the following example: https://code.sololearn.com/chGwxm028M0J/?ref=app When you run that code, notice the behavior of the updates in (1) and (2). Updates to the original variable value do not affect updates to the variables that were subsequently set equal to that variable. However, in (3), notice that the append() method updates q and r, even though it is only explicitly applied to p. This behavior appears to be inconsistent with (1) and (2). Can anyone clarify the rationale for this apparent discrepancy? I checked the python documentation but did not find an explanation.
2 Antworten
+ 1
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
(text above copied from https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/python_lists.asp
As for the strings;
when you update 'a' the old 'a' gets sort of 'destroyed' so 'a' now is a completely new variable.
Do a print(id('a') before an after the update and do the same for the lists too and notice the output.
0
Here is a related example:
# What is the output of this code, and why?
a = '1'
b = '2'
b = a
a = '3'
c = ['1']
d = ['2']
d = c
c = [b + '3']
for e in d: print(e)
# choices:
# 13
# 1
# 33
# 23