Global Variable Python
<pre><code>A=[]

def main():
    global A
    A=[1,2,3,4,5]
    b()

def b():
    if(len(A)&gt;0):
        A=[7,8,9]
    else:
        if(A[3]==4):
            A.remove(2)

main()  
</code></pre>

<p>This code gives error in line A.remove(2) giving reason:"UnboundLocalError: local variable 'A' referenced before assignment"</p>

<p>but A list is global and for sure it has been initialized in main() function.Please explain why this is giving error?</p>

<p>As A has been initialized again in b function, will this cause error?</p>

<p>You must declare a variable <code>global</code> in any function that assigns to it.</p>

<pre><code>def b():
    global A
    if some_condition:
        A.append(6)
    else:
        A.remove(2)
</code></pre>

<p>Without declaring <code>A</code> <code>global</code> within the scope of <code>b()</code>, Python assumes that <code>A</code> belongs in the b() namespace. You can read it, but cannot edit it (any changes made will not persist to the <em>true</em> <code>A</code>.</p>

<p>You're allowed to set A to something inside the function <code>A = ...</code> will work, but <strong>only</strong> within the scope of the function.</p>

<p>If you try to mutate A inside of the function without defining A in your function's namespace, then Python will tell you that you are trying to mutate a variable outside of your purview with <code>UnboundLocalError</code></p>

<p>By declaring <code>A</code> <code>global</code>, the interpreter knows that you mean to edit the global variable.  </p>

<p>I'm assuming that you meant for your code to look something like this (Otherwise, it runs fine)</p>

<pre><code>A=[]

if __name__ == '__main__':
    def main():
        global A
        A=[1,2,3,4,5]
        b()

    def b():
        global A
        if some_condition:
            A=[7,8,9]
        else:
            A.remove(2)
        print A

    main()
    print A

print A
</code></pre>

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