UnboundLocalError when using + = but not an add list

I do not quite understand the difference between the following two similar codes:

def y(x):
    temp=[]
    def z(j):
        temp.append(j)
    z(1)
    return temp

call y(2)returns[1]

def y(x):
    temp=[]
    def z(j):
        temp+=[j]
    z(1)
    return temp

the call y(2)returns UnboundLocalError: local variable 'temp' referenced before assignment. Why +does the operator generate an error? Thanks

+4
source share
2 answers

Answer the header, the difference between + and "append":

[11, 22] + [33, 44,] 

will provide you with:

[11, 22, 33, 44]

and.

b = [11, 22, 33]
b.append([44, 55, 66]) 

will provide you

[11, 22, 33 [44, 55, 66]] 

Error response

This is because when you assign a variable in scope, this variable becomes local to that scope and the shadow of any similar named variable in the outer scope

temp+=[j] temp = temp +[j]. temp . . python.

.:)

+9

UnboundLocalError , , , Python .

append , .

+3

Source: https://habr.com/ru/post/1618987/


All Articles