-2

When I execute this code, the "list" argument is changed in the main module, but the the "i". Why? How can I change the "i" argument in the module ?

def func2(list, i):
    print (list, i)
    list += [4,1]
    i += 1
    print(list, i)
    return

j = 1
l = [0,1]
func2(l, j)
print("---",l , j)

Thanks to @JBernardo for the tip. The real solution is to put the variable in a list. Now I can change both arguments and that is what I wanted.

def func2(list, i):
    print (list, i)
    list += [4,1]
    i[0] = i[0]+1
    print(list, i[0])
    return

j = [1]
l = [0,1]
func2(l, j) 
print("---",l , j[0])
JLB
  • 3
  • 2

1 Answers1

2

Lists are mutable. You are changing their contents. A number is immutable, so you have to set it as global before to access outer scope

def func():
    global var1, var2
    var1 += [1,2,3]
    var2 = 5


var1 = [0, 1]
var2 = 7
func()

In this case the function receives no arguments since you want to change the global state

JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • 1
    I would not link mutability to scope and namespaces necessarily. In fact, in your example you have removed both arguments from the signature of the function – Pynchia Mar 15 '18 at 13:28
  • @Pynchia Those are 2 different issues I addressed with the same solution, instead of doing one thing for each variable which would confuse a beginner – JBernardo Mar 15 '18 at 13:30
  • @JBernardo My understanding is that there is no way to keep the arguments and have j incremented ? – JLB Mar 15 '18 at 13:33