I have this code:
def h(l1,l2):
l1.pop()
l2 = l2 +l1
l1=[1,2,3]
l2=[]
h(l1,l2)
print (l1,l2)
Why after running the code, l1 is [1,2] and l2 remain the same ([]).Why l2 is not [1,2]?
This happens as l2 is local to your h function, so the l2 outside the function doesn't know that you changed some other variable even if they have the same name, although their scope is different.
Is this what you expected to happen?
def h(l1,l2):
l1.pop()
l2.extend(l1 +l2)
l1=[1,2,3]
l2=[]
h(l1,l2)
print (l1,l2)
>>> '[1, 2] [1, 2]'
In this case i don'r define an new variable, i'm changing the existing l2 inside the function. so that way, l2 inside the function and outside the function are actually the same.