Search code examples
pythonscopeglobal-variables

How to update a variable inside a function?


I have a question about two different ways of writing a piece of code. I want to know whether they are both okay or one is better under some conditions? Basically, is it better to give the variable we want to update to the function or not?

def f1(num):
    output.append(num)

output = []
f1(2)
print(output)

and

def f1(num, output):
    output.append(num)

output = []
f1(2, output)
print(output)

Solution

  • In the first example, your function works for only adding element to globally defined certain array. And it is not good approach, you cannot use it for another array.

    Second one has generic approach which is better. But only one small correction; you have an array named output, and you pass it to your function, but you keep its name same in your function. So, for your function, there are two output one global and one local, better use different names in this case:

    output = []
    
    def f1(num, arr):
        arr.append(num)
    
    f1(2, output)
    print(output)
    

    Please see warning PyCharm shows in same naming case:

    enter image description here