Search code examples
pythonglobal-variables

Changing globally defined list as locally


I have a question about the python variables. As you see below, I have defined with L a list and with I an integer variable after that, i have added new number to list inside function as locally.I can use the changed list outside the function as globally; on the other hand same situation is not for the integer variable. Can someone help me please ? What is the difference? PS:I know that ,I use integer variable inside the function as local variable because of that, it doesn't change on global. but why not a list variable?

L=[] 
I=5
def change_var(I,L):
    I=10
    L.append(12)
    print('Inside function I',I)
    print('Inside function L',L)
    return I,L
change_var(I,L)
print('Outside function I',I)
print('Outside function L',L)



Result

>>>Inside function I 10
>>>Inside function L [12]
>>>Outside function I 5
>>>Outside function L [12]```

Solution

  • If a variable gets affected a value anywhere inside the body of a function (as in variable = ...), then it is considered to be local, unless you explicitely declare it global in this function.

    You treat I and L very differently:

    • You assign a value to I in I = 10, so it is considered local, and so a different variable from the other, global I. The changes you make to it can't be reflected on the other, global I. If you wanted to act on the global I, you should have declared global I at the start of your function.

    • You don't assign anything to L, you just mutate the unique, already existing global list.