In your code count1
is the reference of the list and with count1[0]
you try to access the 0th index of the count1
list. Hence, when you do:
count1[0] = count1[0]+1
you are accessing the same count1
object defined outside the b()
function.
But that's not the case with count2
. When you do:
count2 = count2 + 1
You are trying to create a new count2
object and in this case b()
won't read the value of count2
from the outer scope. In order to access the count2
from the outer scope, you may use nonlocal
keyword (available since Python 3.x). Hence, your code should be as:
# For Python 3.x
def a():
count2=0
def b():
nonlocal count2
# ^ used here
count2 = count2+1
b()
But since you are using Python 2.x and nonlocal
is not available in it, you may do a workaround via using dict
to store count2
variable as:
# Workaround for Python 2.x
def a():
nonlocal_dict = { # `dict` to store nonlocal variables
'count2': 0
}
def b():
nonlocal_dict['count2'] = nonlocal_dict['count2']+1
# ^ this `dict` will be available here
b()
Please also take a look at: