+ 2
[UNSOLVED]Modifying list in function
We can modify list using remove pop append but adding doesn't work in functions? ''' a=[1,2,3] def func(x): a+=[x] # THIS CODE GIVES ERROR func(4) print(a) ''' a=[1,2,3] def func1(x): b=a b+=[x] #THIS CODE WORKS func1(4) print(a)
5 ответов
+ 2
Prabhas Koya
That's why python list has append.
in first case you are getting error "UnboundLocalError" so to avoid that we need to make 'a' global inside function:
a=[1,2,3]
def func(x):
global a
a+=[x] # THIS CODE GIVES ERROR
func(4)
print(a)
#now this will work
I hope this link will help you:
https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs-closure
+ 1
What about second code..?
Assigning b=a and changing b will change the a why? I didn't globalise the list but it's changing?, what is happening in the internals?
+ 1
Prabhas Koya
In the second case 'b' is a local variable and you assigned reference of 'a' to 'b' so whatever you will do with 'b' that would be affect in 'a' because of same reference. Since 'b' is already a local variable so we are not getting any error like we got in first case.
+ 1
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟
Why does append work ?
+ 1
Prabhas Koya
append does not create new list, it just add new item at the end of the list. So we don't get any error.
'+' operator means concatenation which always creates a new list.
You need to read this:
https://www.quora.com/When-should-we-use-append-or-the-+-operator-to-concatenate-lists-in-JUMP_LINK__&&__Python__&&__JUMP_LINK
In the first case, you are creating a new list (a + [x]) and then assigning to 'a' which behaves as a local variable.
Read this statement 'If there is an assignment to a variable inside a function, that variable is considered local'.
So as I told in my first reply we get error 'UnboundLocalError' when assigned new list to a local variable.