Reputation: 53
In my understanding, the above two pieces of code should have the same effect. But why when I let a point to another array, the results could be different? The following code illustrates the difference:
# part 1
a=[1,2]
b=a
a=a+[3] # a points to a new array. b should still points to [1,2]
print(a, b) # [1, 2, 3] [1, 2]. My expected result.
# part 2
a,b=[1,2],a
a=a+[3] # a points to a new array. b should still points to [1,2]
print(a, b) # [1, 2, 3] [1, 2, 3]. Why the result is different from the above?
I'm surprised by the result of the part 2. Could someone please explain why the results are different? Thank you so much in advance!
EDIT: Thank you so much for everyone! Now I understand the problem! Thanks so much!
Upvotes: -1
Views: 444
Reputation: 51
This is happening because you are running both part_1 and part_2 at the sametime in the same environment.
Now In this line a, b = [1,2], a
List [1,2]
is being assigned to a
but the part_1 value of a
is assigned to b
which is [1,2,3]
. Because of this reason, you are getting [1, 2, 3], [1, 2, 3]
for both a
and b
.
Now if you try to run part_2 seperately you will run into a nameError
because in part_2, a=[1,2]
and b=a
are being executed at the sametime. Which means that the a
is not yet assisned to [1,2]
when it is being assigned to variable b
.
Upvotes: 0
Reputation: 308452
You need to understand the order of operations.
The expression [1,2],a
is building a tuple with two elements. The first element is the list [1,2]
and the second element is the existing value of a
which was set in part 1 to [1,2,3]
.
Now that tuple is unpacked by the assignment, so a = [1,2]
and b=[1,2,3]
.
Then you modify a
so it coincidentally is the same as b
.
The whole process would have been much clearer if you'd used different constants in the two parts of your test.
# a=[1,2,3] from part 1
a,b=[4,5],a
a=a+[6]
print(a,b) # [4, 5, 6] [1, 2, 3]
Upvotes: 2
Reputation: 11
Are you running the whole code in a time? If you are doing this, thhe confusion is easily explained.
When you set b = a in the second part, it takes the actual a value, which is [1,2,3] due to the first part.
Upvotes: 0
Reputation: 2121
The line
a,b=[1,2],a
assigns [1,2]
to a
, and assigns the previous value of a
to b
.
This means b
will have the previous value of a
, which is [1, 2, 3]
Upvotes: 2
Reputation: 70347
You need to run your tests in isolated environments. Your "part 2" test is grabbing the a
value from "part 1".
Upvotes: 3
Reputation: 15206
Well, a
was already [1, 2, 3]
from "part 1" so when you assign that to b
in "part 2", of course b
is going to be [1, 2, 3]
...
Upvotes: 0