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]
>>> 
DSM
  • 342,061
  • 65
  • 592
  • 494
Gaurav
  • 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. – anon582847382 Apr 14 '14 at 18:53

2 Answers2

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.

Elektito
  • 3,863
  • 8
  • 42
  • 72
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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 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 Apr 14 '14 at 19:00
  • @Gaurav: Strings and small integers are subject to interning. See, for example, http://stackoverflow.com/questions/15541404/python-string-interning – NPE Apr 14 '14 at 19:00
  • @Blckknght: D'oh. Copy and paste error. Thanks for pointing out. :) – NPE Apr 14 '14 at 19:19