2

How to determine an ID on Python?

I heard that the same strings have the same IDs like below:

>>>list1=[1,2,'aaa','bbb']
>>>list2=[3,4,'aaa','bbb']
>>>id(list1[2])
12345
>>>id(list2[2])
12345

but the following case does not hold the rule:

>>>list1=[1,2,'Hello World','bbb']
>>>list2=[3,4,'Hello World','bbb']
>>>id(list1[2])
12345
>>>id(list2[2])
12367

How are they different from each other?

Added

Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 2, 'aaa', 'bbb']
>>> list2 = [2, 3, 'aaa', 'bbb']
>>> id(list1[2])
4511557072
>>> id(list2[2])
4511557072
>>> list3 = [1, 2, 'Hello World', 'bbb']
>>> list4 = [2, 3, 'Hello World', 'bbb']
>>> id(list3[2])
4511542272
>>> id(list4[2])
4511542368
Arena Son
  • 95
  • 1
  • 8
  • This almost never matters with immutable objects like strings. What do you need the strings' IDs for? – user2357112 Mar 31 '15 at 05:25
  • i just wonder what makes the different :) – Arena Son Mar 31 '15 at 05:27
  • Also, when posting interpreter session transcripts, please copy-paste from an actual interpreter session rather than making up output. Made-up output is frequently wrong in crucial ways. – user2357112 Mar 31 '15 at 05:29
  • Please show a reproducible example. As @Marcin stated, your second snippet does not execute. – Amadan Mar 31 '15 at 05:29
  • You might have the wrong concept about `id` there. It points to a memory location at which the String is stored. See: http://stackoverflow.com/questions/2123925/when-does-python-allocate-new-memory-for-identical-strings or http://stackoverflow.com/questions/24245324/about-the-changing-id-of-a-python-immutable-string – Calon Mar 31 '15 at 05:29
  • @user2357112 , i'm sorry about that, i will chage – Arena Son Mar 31 '15 at 05:31
  • @Calon , thank you for answer. i will see it. – Arena Son Mar 31 '15 at 05:36

2 Answers2

2

Possible reason is that in your second example you use id(lst2[2]) instead of id(list2[2]). But in general I think, its up to python's interpreter to decide whether string objects containing the same string are actually the same string objects or not.

In addition this link has a bit of discussion and answers related to this question.

Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294
-2

Your assumption of same string having the same id is right.

Could you give more details about your code? This is what I have got:

>>> list2=[3,4,'aaa','bbb']
>>> list1=[1,2,'aaa','bbb']
>>> list2=[3,4,'aaa','bbb']
>>> id(list1[2])
4449536920
>>> id(list2[2])
4449536920
Da Tong
  • 2,018
  • 18
  • 25