2

What I mean is, for an integer:

>>> a = 2
>>> def b():
...     a += 1
...
>>> b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in b
UnboundLocalError: local variable 'a' referenced before assignment

While for a list (or say for a list element):

>>> a = [0]
>>> def b():
...     a[0] += 1
...
>>> b()
>>> a[0]
1
1
  • 2
    They have the exact same limitation, as you'd see if you did a comparable operation: a += [1]. Commented Aug 12, 2019 at 21:34

1 Answer 1

3

In the example with the int, Python is attempting to assign something to a in the function b() so it identifies a as a "local" variable in the function. And since the variable a is not yet defined, the interpreter throws the error.

In the example with the list, Python is not attempting to assign anything to a, so the interpreter identifies it as a "global" variable. Yes, it is modifying the values inside the list, but the reference to the list object named a hasn't changed.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer! So is it because integer is not an object so python cannot reference to it and therefore we cannot just increment it? Then what is integer in python? Just called a value type or?
@BillyChen no, that's not why at all. Integers are also objects.
Sorry for the confusion, the only reason the first example doesn't work is because you're redefining a. I've cleaned up my answer to prevent any confusion. Everything in Python is an object. :P
Got it. Thanks @jonrsharpe and Xteven, I will keep learning to understand more!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.