Skip to content Skip to sidebar Skip to footer

Python: List Changes When Global Edited

a = [1] def do(): global a b=a print b a[0] = 2 print b do() outputs: 1 2 I am pretty sure it has something to do with the fact that 'a' is a global list. Co

Solution 1:

In this line b=a you essentially create a reference b, which points to a. This in python does not create a new copy of the list, but just creates a new link to it.

If you want to create a copy of a then you need to do it explicitly. Using list comprehensions, you can do it in this way :

b = a[:]

This will create a copy of a which will be referenced by b. See it in action :


>>>a = [1]>>>b = a #Same list>>>a[0] = 2>>>b
[2] #Problem you are experiencing

You can see for yourself whether they refer to the same object or not by :

>>> a is b
True

The true signifies that they refer to the same object.

>>>b = a[:] #Solution <<--------------

Doing the same test again :

>>> a is b
False

And problem solved. They now refer to different objects.

>>>b
[2]
>>>a[0] = 3#a changed>>>a
[3]
>>>b
[2] #No change here

Solution 2:

When you assign b = a you are copying the reference to a list object that is held in a to b, so they point at the same list. The changes to the underlying object will be reflected by either reference.

If you want to create a copy of the list use

b = list(a)

or, a method that will work on most objects:

importcopy
b = copy.copy(a)

Solution 3:

I think you have a misunderstanding of python's variable model. This is the article I read that made it click for me (the sections "Other languages have variables" and "Python has names").

Post a Comment for "Python: List Changes When Global Edited"