-5

Can anyone explain the reason why python behaves differently in the following two cases please? Much appreciation.

def modifyNone(x):
    print("B4:"+str(x))
    # x.append(5)
    x=[5]
    print("In:"+str(x))

a = []
modifyNone(a)
print("After:"+str(a))

Output:

B4:[]
In:[5]
After:[]

Method:

def modifyNone(x):
    print("B4:"+str(x))
    x.append(5)
    # x=[5]
    print("In:"+str(x))

a = []
modifyNone(a)
print("After:"+str(a))

Output:

B4:[]
In:[5]
After:[5]
Rui Zheng
  • 189
  • 6

1 Answers1

3

Python is pass by value, so you'll have to reassign a returned value like so:

a = modifyNone(a) # where the function returns a value

You don't seem to understand variable scope as well, try the documentation.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70