Namespace questions: Mutable variable doesn't need to be declared as global in function?
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>

<p><strong>ex1:</strong></p>

<pre><code>def func1():
    a = 1
    b.add('b')

a = 0
b = set()
func1()
print(a,b) 
</code></pre>

<p>the result is 0 {'b'}</p>

<p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p>

<p><strong>ex2:</strong></p>

<pre><code>def func1():
    b.add('b')

def func2():
    b = set()
    func1()

func2()
print(b)

Traceback (most recent call last):
Â  File "test_variables.py", line 10, in &lt;module&gt;
Â  Â  func2()
Â  File "test_variables.py", line 8, in func2
Â  Â  func1()
Â  File "test_variables.py", line 4, in func1
Â  Â  b.add('b')
NameError: name 'b' is not defined
</code></pre>

<p>why in this case, b cannot be assigned in func1()? </p>

<p><strong>ex3:</strong></p>

<p>I have to pass the variable from function to function </p>

<pre><code>def func1(b):
    b.add('b')

def func2():
    b = set()
    func1(b)
    print(b)

func2()
</code></pre>

<p>it prints {'b'} this time</p>

<p><strong>ex4:</strong></p>

<p>what I can also do is to define b outside</p>

<pre><code>def func1():
    b.add('b')

def func2():    
    func1()
    print(b)

b = set()
func2()
</code></pre>

<p>it prints {'b'} as well</p>

<p>thanks in advance for your kind help </p>

<p>When you pass a mutable variable to a function you pass if by reference, which means you're creating another variable (which exist only in the scope of the function) which points to the same object.</p>

<p>Moreover, Python works in a way that you can use and see variables that are in you're outer scope (that's why in <code>ex1</code> you are able to add things to </p>

<p>In <strong>EX1</strong>, <code>func1()</code> knows <code>a</code> and <code>b</code> but cannot assign values to them (unless you define them as <code>global</code> inside the function!). When you're doing <code>a = 1</code>, python just creates a new <code>a</code> variable that lives inside that function only.<br>
<code>b.add('b')</code> is possible because you're referring to the <code>set</code> object (which is no mutable). If you'll try to to something like <code>b = 'b'</code> inside the function you will, again, create a local <code>b</code> variable and leave the outer set untouched.</p>

python