-2

discription about id():

Help on built-in function id in module builtins:

id(obj, /) Return the identity of an object.

This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)

but I found a strange thing as below:

>>> id([2222]) == id([2222])
True
>>> id([2222]) == id([2223])
True
>>> id([2222]) == id([2224])
True
>>> id([2222]) == id([2225])
True
>>> id((12, 12)) == id((12, 12))
True
>>> id((12, 12)) == id((12, 13))
False
>>> id([12, 12]) == id([12, 13])
True
>>> a = [12, 12]
>>> b = [12, 13]
>>> id(a) == id(b)
False

who can explain this?

lwenkun
  • 31
  • 1
  • 8
  • 1
    and replace the image to the text [why-not-upload-images-of-code](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – Brown Bear Sep 30 '18 at 07:59

1 Answers1

4

When you do

id([2222]) == id([2223])

Python creates a new list, gives it a single member (2222) and checks its ID (memory address). Then (since the list is not used again) it discards the list. Now it creates another new list in the same memory location as the old one, adding 2223 as its sole member. The ID will be the same since the list is built at the same memory address.

This doesn't work with tuples since they are immutable/constant and therefore get their own ID.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 3
    The documentation quoted in the question even hints at this: The vaues returned by `id` are only unique for "simultaneously existing objects." The lists being created in the question are not simultaneously existing, so there is no guarantee that their id's will be unique. – Blckknght Sep 30 '18 at 08:04