Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Updating Global variables

Tags:

python

numpy

Could anyone tell me what I am doing wrong in my code. How come, I cannot update my global variable? To my understanding, if it is a global variable I can modify it anywhere.

If the numpy is creating a new array (when I use np.delete), what would be the best way to delete an element in an numpy array.

import numpy as np

global a
a = np.array(['a','b','c','D'])
def hello():
    a = np.delete(a, 1)
    print a

hello()
like image 274
Jesh Kundem Avatar asked Sep 25 '26 19:09

Jesh Kundem


1 Answers

If you want to use a global variable in a function, you have to say it's global IN THAT FUNCTION:

import numpy as np

a = np.array(['a','b','c','D'])
def hello():
    global a
    a = np.delete(a, 1)
    print a

hello()

If you wouldn't use the line global a in your function, a new, local variable a would be created. So the keyword global isn't used to create global variable, but to avoid creating a local one that 'hides' an already existing global variable.

like image 165
Jacques de Hooge Avatar answered Sep 27 '26 10:09

Jacques de Hooge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!