how to append item to a global list from within a procedure

append, global-variables, python

Solution

Just change it to the following:

def proc(n):
    for i in range(0,n):
        C = i
        p.append(C)

The `global` statement can only be used at the very top of a function, and it is only necessary when you are assigning to the global variable. If you are just modifying a mutable object it does not need to be used.

Here is an example of the correct usage:

n = 0
def set_n(i):
    global n
    n = i

Without the global statement in the above function this would just create a local variable in the function instead of modifying the value of the global variable.

Problem

I get a syntax error when i do this: ``` p = [] def proc(n): for i in range(0,n): C = i global p.append(C) ```

Original source