
Python Function and Scope - The function can update outer list, set, dictionary but can't change integer, float, string
Can Python function access or update outer variables? It depends on the type as follows.
a = ''
b = []
def f():
a = 'Apple'
b.append('x')
f()
print(a)
print(b)
a
is string and not hasn't updated by f
. But f
has appended to list b
. So Python function...
- can update the outer list
- can NOT update the outer string
Python function can't update the outer integer, float, string
a = 2
b = 3.14
c = 'JavaScript'
def f():
a = 3
b = 4.5
c = 'PHP'
f()
print(a) # 2
print(b) # 3.14
print(c) # JavaScript
Python function can add the outer list, set, dictionary
a = [5, 9]
b = {'PHP', 'HTML'}
c = {'x': 1, 'y': 2}
def f():
a.append(100)
b.add('CSS')
c['z'] = 3
f()
print(a) # [5, 9, 100]
print(b) # {'CSS', 'HTML', 'PHP'}
print(c) # {'x': 1, 'y': 2, 'z': 3}
You may think the function can only add and can't replace the value. But it can actually update list as follows.
a = [5, 9]
def f():
a[0] = 7
f()
print(a) # [7, 9]
Id and scope
a = [5, 9]
print(id(a)) # 4535348096
def f():
print(id(a)) # 4535348096
a[0] = 7
f()
print(id(a)) # 4535348096
As you see, id of a
is the same in outer or inner scope.
Python function can't update a string but access
a = 'Apple'
def f():
print(a)
f()
# Apple
Comments
Powered by Markdown