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.

2 Answers 2

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] 
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

@colinfang, augmented assignment involves LOAD, STORE operation beside the binary operation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.