Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5705

Use of the global keyword in Python

I have a simple Python script which just multiplies two numbers taken from a list of list and then send the results to another function which then appends them to a list. Below is the code for the same:

results = []

def check_results(result):
    results.append(result)

def multiply(x, y):
    return x * y

if __name__ == "__main__":
    numbers = [[1,1], [2,2], [3,3]]
    for x, y in numbers:
        check_results(multiply(x, y))
    print(results)

My question is should we not use the global keyword inside the check_results function before we add them to the results list which is outside its scope ?

In other words shouldn't the whole code be something like this ?

results = []

def check_results(result):
    global results
    results.append(result)

def multiply(x, y):
    return x * y

if __name__ == "__main__":
    numbers = [[1,1], [2,2], [3,3]]
    for x, y in numbers:
        check_results(multiply(x, y))
    print(results)

Can someone kindly let me know if my understanding is wrong here and what should the global keyword be used for?

Upvotes: 2

Views: 69

Answers (1)

blue note
blue note

Reputation: 29061

Python

  • writes in the local scope
  • reads from the local scope, and if that fails, from the global scope

So, if you wanted to assign the global results variable, you would have to use global results, to specify that you mean the global variable.

However, since you read results, and no such variable exists in your function, the global one is looked up.

Note that, although you append to the list referred to by results, you don't change the actual results variable itself, so what you do is not considered writing.

Upvotes: 5

Related Questions