0

x = 3
x = 4

Is the second line an assignment statement or a new variable binding?

3
  • 1
    "variable binding" is fancy words for "assign the [..] variable". Commented Oct 24, 2014 at 8:13
  • 1
    Can you explain what you think "assignment statement" and "new variable binding" mean? Commented Oct 24, 2014 at 8:22
  • what I mean is that does python mutates the value of the x variable or does it throws away the first x, make a new variable and bind the new value to it. Commented Oct 24, 2014 at 8:31

2 Answers 2

3

There is no difference. Assigning to a name in Python is the same whether or not the name already existed.

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

Comments

2

In (very basic) C terms, when you assign a new value to a variable this is what happens:

x = malloc(some object struct)

If I'm interpreting your question correctly, you're asking what happens when you reassign x - this:

A. *x = some other value

or this:

B. x = malloc(something else)

The correct answer is B, because the object the variable points to can be also referred to somewhere else and changing it might affect other parts of the program in an unpredictable way. Therefore, Python unbinds the variable name from the old structure (decreasing its "reference counter"), allocates a new structure and binds the name to this new one. Once reference counter of a structure becomes zero, it becomes garbage and will be freed at some point.

Of course, this workflow is highly optimized internally, and details may vary depending on the object itself, specific interpreter (CPython, Jython etc) and from version to version. As userland python programmers, we only have a guarantee that

x = old_object

and then

x = new_object

doesn't affect "old_object" in any way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.