0

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
Sudhir Rupapara
  • 11
  • 1
  • 1
  • 3
  • Are you **sure** that that is the code that throws that exception? Because as written, you'd get `UnboundLocalError` instead. – Martijn Pieters Jun 23 '17 at 06:47
  • In other words, you *can't* get a `NameError`, the name is clearly defined in the sample code you posted. More over, the code you posted assigns to the name `globlist` *in the function*, making it a local unless specifically overridden with a `global` statement as described in the answers below. But that only makes sense if you get a different exception for the code you posted. – Martijn Pieters Jun 23 '17 at 06:51
  • Sorry for inconvenience. Yes, it shows following error ` UnboundLocalError: local variable 'globlist' referenced before assignment` – Sudhir Rupapara Jun 23 '17 at 07:21

3 Answers3

4

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.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

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
Shmulik Asafi
  • 203
  • 1
  • 6
0

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

Abijith Mg
  • 2,647
  • 21
  • 35