0

Why is the id is of x changes in the following code while it still has the same value. I expect the id for x and z should be same in this case as the value remains the same at the end.

>>> x = [1, 2, 3]
>>> z = x
>>> id(z) == id(x)
True
>>> x = [1, 2, 3]
>>> id(z) == id(x)
False
>>> x
[1, 2, 3]
>>> z
[1, 2, 3]
>>> 
1
  • 1
    Because rather than modifying the list in-place, you are actually assigning a new value. Hence the new ID, as it now refers to a different object. Commented Apr 14, 2014 at 18:53

2 Answers 2

3

What an object holds has nothing to do with its identity. id(x) == id(y) if and only if x and y both refer to the same object.

Maybe this example helps:

x = [1, 2, 3]
y = [1, 2, 3]
z = y
print x, y, z
y[0] = 1000
print x, y, z

which prints this:

[1, 2, 3] [1, 2, 3] [1, 2, 3]
[1, 2, 3] [1000, 2, 3] [1000, 2, 3]

y and z both refer to the same object, so modifying one variable modifies the value retrieved by the other, too. x remains the same because it's a separate object.

What you shouldn't forget is that initializing a variable with a literal list (like [1, 2, 3]) creates a new list object.

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

Comments

0

Whether or not the two lists contain the same elements does not imply that they should have the same id.

Two variables only have the same id if they refer to the same object, which the second z and x do not:

>>> x = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x[0] = 999
>>> x
[999, 2, 3]
>>> z
[1, 2, 3]

This demonstrates that x and z are two distinct, unrelated lists.

3 Comments

Thanks for the response... do you mean this behavior for list is different for strings/integers.. that's what it appears: >>> x = [1,2,3] >>> y = [1,2,3] >>> id(x) 47581304 >>> id(y) 3594880 >>> x = "foo" >>> y = "foo" >>> id(x) 46246208 >>> id(y) 46246208 >>>
@Gaurav: Strings and small integers are subject to interning. See, for example, stackoverflow.com/questions/15541404/python-string-interning
@Blckknght: D'oh. Copy and paste error. Thanks for pointing out. :)

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.