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>The reason you are getting this is because when you performed this assignment in your function: </p>

<pre><code>A = [7, 8, 9]
</code></pre>

<p>The interpreter will now see <code>A</code> as a locally bound variable. So, what will happen now, looking at this condition:</p>

<pre><code>if(len(A)&gt;0):
</code></pre>

<p>Will actually throw your first <code>UnboundLocalError</code> exception, because, due to the fact, as mentioned, you never declared <code>global A</code> in your <code>b</code> function <em>and</em> you also created a locally bound variable <code>A = [7, 8, 9]</code>, you are trying to use a local <code>A</code> before you ever declared it.</p>

<p>You actually face the same issue when you try to do this:</p>

<pre><code>A.remove(2)
</code></pre>

<p>To solve this problem with respect to your code, simply declare the <code>global A</code> back in your <code>b()</code> function.</p>

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

<p>However, the better, ideal and recommended way to do this is to not use global and just pass the arguments to your function</p>

<pre><code>A = [1, 2, 3, 4]


def main(list_of_things):
    # do whatever operations you want to do here
    b(list_of_things)

def b(list_of_things):
    # do things with list_of_things

main(A)
</code></pre>

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