0

Why it trows the error "local reference 'a' referenced before assignment"?

#this trows that error a= [1,2,3] def add(n): a+=[n] add(4) print(a) #but if instead of a+=[n], I put a.extend([n]), it works. What is happening here?

8th Jan 2022, 2:53 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
4 Respostas
+ 1
I think a (which is a list) is accessible inside and outside the function cause it is declared before using the method extend, so you can apply this method that exists in <class list> without a problem, but when you tried a+= it's like you try to define a new variable called a and you add it to it self ( 'a' as a new variable doesn't have a value so a+= will return an error). if you put a = a +1 a should already have a value or it will return the error you've got.
8th Jan 2022, 4:06 PM
YoPycode
+ 1
if you want to modify a inside the function make it global by adding global a inside the function. without it you'll manipulate just local variables inside the function. def add(n): global a a+=[n]
8th Jan 2022, 3:15 PM
YoPycode
+ 1
Well, now it makes more sense, but it is still a tricky one...thanks for the help!
8th Jan 2022, 4:47 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
0
But a.extend([n]) inside the function wouldn't also modify a? And it works
8th Jan 2022, 3:21 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar