mercredi 13 juillet 2016

Python local variable is changing global variable. Why?


Strange behavior on python. Local variable is changing the global variable.

import numpy as np

xc = np.arange(10)

def func(xc,val=3):
  xc /= val
  return xc

print xc
c = func(xc)
print xc

I can fix it using .copy() function as:

import numpy as np

xc = np.arange(10)

def func(Xg,val=3):
  xc = Xg.copy()
  xc /= val
  return xc

print xc
c = func(xc)
print xc

There's a better another way to avoid this problem?


Aucun commentaire:

Enregistrer un commentaire