5

The first code snippet prints [0, 3] out.

def func():
    a = [0]

    def swim():
        a.append(3)
        # a = [1]+a
        return a
    return swim()

print(func())

The second code snippet raises error "UnboundLocalError: local variable 'a' referenced before assignment"

def func():
    a = [0]

    def swim():
        # a.append(3)
        a = [1]+a
        return a
    return swim()

print(func())

Is a visible/accessible to function swim after all?

Liang Li
  • 133
  • 1
  • 9

3 Answers3

4

It seems this is a commonly asked question as stated in this link. The reason is that variable a inside swim becomes a local variable as soon as there is an assignment to a. It shadows the external a, and local a is not defined before assignment in function swim, so the error rises.

Thanks for all your guys' answers!

Liang Li
  • 133
  • 1
  • 9
-1

When you do such assignment such as a = [1] + a or a += [1] in a scope, the variable would become local to that scope. In your case, that is function swim().

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Trickee
  • 81
  • 7
-2

You are appending an element in the first code. The id of a is still same.

But at second code, you are re-defining variable a, which is changing the id of that variable. So that you get UnboundLocalError.

GLHF
  • 3,835
  • 10
  • 38
  • 83