lists: += vs. .append() & oddness with scope of variables

Duncan Booth duncan.booth at invalid.invalid
Sun Mar 5 13:22:48 CET 2006

Sandro Dentella wrote:

> I'd like to understand why += operator raises an error while .append()
> does not. My wild guess is the parses treats them differently but I
> cannot understand why this depends on scope of the variables (global
> or class variables):
> a = [0]
> class foo(object): 
>     def __init__(self):
>         print "a: ", a
>         # += does not work if 'a' is global
>         #a += [1]
>         a.append(2)
>         print "a= ", a

Any assignment to a variable within a function means that the name to which 
you are assigning is regarded as a local variable (unless you use the 
'global' statement to override that). += is a form of assignment, calling 
the append method is not an assignment.

The solution here is simply to use 'global a' to tell the compiler that you 
meant to assign the the global variable rather than creating a new local 

More information about the Python-list mailing list