python global variable not defined in for loop

global-variables, python, python-2.7, python-3.x

Solution

You can access global variable from inside `foo`, but you can't rebind them unless the `global` keyword is used

So you can use `LINES.append(...)` or `LINES[:] = []` as they are merely modifying the list that LINES references.

When you try to assign to `LINES` using `LINES = []`, Python knows it needs to create an entry for LINES in the functions local variables. Since you are trying to use `len(LINES)` before assigning anything to the local variable, it causes an error

You can inspect `foo` like this

>>> foo.func_code.co_nlocals
2
>>> foo.func_code.co_varnames
('prob', 'LINES')

If you define `foo` again without the `LINES = []`, you'll see that Python no longer marks it as a local variable.

Problem

This code gives the error: `UnboundLocalError: local variable 'LINES' referenced before assignment` but `LINES` is clearly initialized since if I comment out the line below the print statement it throws no errors and prints `len(lines) = 0` as expected. Am I not understanding something about python?? Whats going on here? ``` LINES = [] def foo(): for prob in range(1,3): print "len(lines) = %d" % len(LINES) LINES = [] if __name__ == "__main__": foo() ```

Original source