1
def test():
    a = [1,2,3]
    def test2():
        a += [4,5]
    test2()
    print a
test()

In my thoughts, a += [4,5] would be equivalent to a.extend cus it is in-place Concatenating two lists - difference between '+=' and extend()

However, use += triggers an error, but extend works fine.

Am I wrong?

Update

I believe I found the reason.

operator.iadd(a, [4,5]) works fine.

So I believe internally a+=[4,5] is interpreted as a = operator.iadd(a, [4,5]), and here comes the assignment.

Community
  • 1
  • 1
colinfang
  • 20,909
  • 19
  • 90
  • 173

2 Answers2

1

The presence of an assignment to a (such as a += [4,5]) in test2 causes Python to create an a variable local to test2, which is never initialized. In Python 3, you would be able to declare nonlocal a in test2 to get around this. In Python 2, you have to use extend or workarounds where you put a in a 1-element list and use

a[0] += [4, 5]
user2357112
  • 260,549
  • 28
  • 431
  • 505
0

According to Why am I getting an UnboundLocalError when the variable has a value?:

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable.

And according to Augmented assignment statements:

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target.

falsetru
  • 357,413
  • 63
  • 732
  • 636