-1

So this is basically how the code works that I'm using.

global Gvar
Gvar = ["Hello"]

def someFunction():
    Lvar = Gvar
    Lvar.append("World")
    print(Lvar)
    print(Gvar)

someFunction()

This outputs "Hello World" twice. How can I prevent the change of the global variable when I change the local?

Thanks in advance, I hope someone can help me out.

GreenSaber
  • 1,118
  • 2
  • 26
  • 53

2 Answers2

0

The problem here is the following line:

Lvar = Gvar

Since Gvar is a list and therefore a complex datatype, Python won't copy the value but instead references to the variable. So whether you modify Lvar or Gvar won't make a difference at this point. Instead, you probably want to copy the values which you can achieve in different ways, e.g.:

Lvar = Gvar[:]

Alternatively, you can use the copy module. Check out the Python FAQs for more information on this.


For completion, this is how your modified code would look:

global Gvar
Gvar = ["Hello"]

def someFunction():
    Lvar = Gvar[:]
    Lvar.append("World")
    print(Lvar)
    print(Gvar)

someFunction()

As a side note, variable names in Python should be lower-case - upper-case is typically used for class definitions only.

m_____z
  • 1,521
  • 13
  • 22
0

You can use shallow copy to do htis task :

global Gvar
Gvar = ["Hello"]

def someFunction():
    Lvar = Gvar.copy()

    Lvar.append("World")
    print(Lvar)
    print(Gvar)

someFunction()

Output :

['Hello', 'World']
['Hello']

You also use deepcopy to do this task :

import copy
global Gvar
Gvar = ["Hello"]

def someFunction():
    Lvar = copy.deepcopy(Gvar)
    Lvar.append("World")
    print(Lvar)
    print(Gvar)

someFunction()

Output :

['Hello', 'World']
['Hello']

N.B : if you use Python 2.7.6 then use print Lvar instead of print(Lvar) and print Gvar instead of print(Gvar).

Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45