Python – access global list in function

Question:

I am new to Python, Before this, I was using C.

def cmplist(list): #Actually this function calls from another function
    if (len(list) > len(globlist)):
        globlist = list[:] #copy all element of list to globlist

# main
globlist = [1, 2, 3]
lst = [1, 2, 3, 4]
cmplist(lst)
print globlist

When I execute this code it shows following error

    if (len(list) > len(globlist)):
NameError: global name 'globlist' is not defined

I want to access and modify globlist from a function without passing it as an argument. In this case output should be

[1, 2, 3, 4]

Can anyone help me to find the solution?

Any suggestion and correction are always welcome.
Thanks in advance.

Edit:
Thanks Martijn Pieters for suggestion.
Origional error is

UnboundLocalError: local variable 'globlist' referenced before assignment
Asked By: Sudhir Rupapara

||

Answers:

You can do:

def cmplist(list): #Actually this function calls from another function
    global globlist
    if (len(list) > len(globlist)):
        globlist = list[:] #copy all element of list to globlist

It could be more Pythonic to pass it in and modify it that way though.

Answered By: Simeon Visser

You need to declare it as global in the function:

def cmplist(list): #Actually this function calls from another function
    global globlist
    if len(list) > len(globlist):
        globlist = list[:] #copy all element of list to globlist

# main
globlist = [1, 2, 3]
lst = [1, 2, 3, 4]
cmplist(lst)
print globlist
Answered By: Shmulik Asafi

Inside function cmplist, object ‘globlist’ is not considered to be from global scope. Python interpreter treats it as a local variable; the definition for which is not found in function cmplist. Hence the error.
Inside the function declare globlist to be ‘global’ before its first use.
Something like this would work:

def cmplist(list):
     global globlist
     ... # Further references to globlist

HTH,
Swanand

Answered By: Swanand Pashankar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.