Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 943
user2250337 Avatar asked Apr 05 '13 19:04

user2250337


Video Answer


1 Answers

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.

like image 97
Andrew Clark Avatar answered Oct 23 '22 12:10

Andrew Clark