1

I have the following Python code snippet:

# code 1
# makes an error

def func1():
    a += 1
a = 1

try:
    func1()
    print(a)
except UnboundLocalError as e:
    print(e)
# code 2
# makes no errors

def func2():
    b.append(1)
b = []
func2()
print(b)

In this code, I observe that a does not change its value, while b behaves like a global variable. I would like to understand the reason behind this difference in behavior.

In the first code snippet, when the func1() function tries to increment the value of a using a += 1, it raises an UnboundLocalError exception. On the other hand, in the second code snippet, the func2() function successfully appends an element to the list b.

I want to know why the first code snippet raises an error while the second code snippet works correctly. Can you explain the underlying reason for this behavior?

I would appreciate any insights or explanations regarding this issue. Thank you in advance!

I expected that the key difference between a and b is that a is an immutable object whereas b is a mutable one.

심재승
  • 11
  • 1
  • "I expected that the key difference between a and b is that a is an immutable object whereas b is a mutable one." that is in fact not the case :) (assignment vs method call is what's important here) – SuperStormer Jun 14 '23 at 06:48

0 Answers0