Understanding Python Variables Assignment
If I execute this code: a = [1,2,3] b = a b.remove(2) print(a,b) What I expect to see is: [1,2,3] [1,3] But this is what I really get: [1,3] [1,3] Why calling b.remove(2) also a
Solution 1:
When you do b = a
, you simply create another reference to the same list. So any modifications to that list will affect both a
and b
. So doing b.remove(2)
will affect the single list that you have.
If you want to get your expected results, you can create a copy of the list:
b = a[:]
This way, you create a copy of the list, and you can modify one without changing the other.
>>>a = [1,2,3]>>>b = a[:]>>>b.remove(2)>>>print a,b
[1, 2, 3] [1, 3]
Solution 2:
a
and b
are two names for the same list, so if you change the list through one name, you can see the changes through the other name. If you want them to be different lists, make a copy:
b = a[:]
or
b = list(a)
Post a Comment for "Understanding Python Variables Assignment"