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?

1
  • 1
    @Pythonista Thanks! It seems 'a' becomes a local variable as soon as there is an assignment. Commented May 27, 2016 at 3:17

3 Answers 3

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!

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

Comments

-1

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.

Comments

-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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.