+ 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)

21st Nov 2021, 10:53 AM
Prabhas Koya
5 odpowiedzi
+ 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
21st Nov 2021, 11:03 AM
A͢J
A͢J - avatar
+ 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?
21st Nov 2021, 11:59 AM
Prabhas Koya
+ 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.
21st Nov 2021, 1:03 PM
A͢J
A͢J - avatar
+ 1
21st Nov 2021, 1:18 PM
Prabhas Koya
+ 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.
21st Nov 2021, 2:32 PM
A͢J
A͢J - avatar