0
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. Could someone please explain to me why the variable b changes when the global changes. And how i could possibly stop it from happening?

an extension to the question: how would you handle further nesting, such as:

a = []
b = []
def do():
    global a, b
    b.append(a[:])
    print a, b
    a[0][0] +=1
    print a, b

a.append([1])
do()
Calum
  • 2,110
  • 2
  • 22
  • 39

3 Answers3

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
asheeshr
  • 4,088
  • 6
  • 31
  • 50
0

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:

import copy
b = copy.copy(a)
tacaswell
  • 84,579
  • 22
  • 210
  • 199
0

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").

bgschiller
  • 2,087
  • 1
  • 16
  • 30