2

Let me have a string object a="ABC". Now I want to create a different object b="ABC" having both id(a) and id(b) separate. Is it possible in python?

Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36

3 Answers3

3

This is an implementation detail. If two variables refer to the same object (a is b is true) then they have to be equal (a == b shall be true). But at least for immutable objects, Python does not specify what it does.

The standard CPython implementation uses common ids for small integers:

a = 1
b = 1
a is b   # True

The rationale is that they are likely to be used in many places in the same program, and sharing a common variable saves some memory.

It is done too for strings, when the interpreter can easily guess that they will share the same value. Example on a Python 3.6

a = "abc"
b = 'ab' + 'c'
c = ''.join((chr(i) for i in range(65, 68)))
a is b      # gives True
a is c      # gives False

TL/DR: whether two equal strings share same id is an implementation detail and should not be relied on.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

This is a great source for id of strings:

>>> a = 'python'
>>> id(a)
4400931648
>>> b = a.encode().decode()
>>> b
'python'
>>> id(b)
4400931984
>>> print('Eureka!')
Eureka!

or:

>>> a = 'python'
>>> b = (a + '.')[:-1]
>>> id(a)
4400931648
>>> id(b)
4400931760
>>> print('Eureka!')
Eureka!

But the general conclusion is that you should not use this even if it is possible.

sampers
  • 463
  • 4
  • 11
0

Python id() returns the integer which acts as identity of that object.

To answer the question in short:

Try to create string "ABC" by slicing.

>>> a = "ABC"
>>> id(a)
4427474416
>>> b = "ABC"
>>> id(b)
4427474416
>>> b = a[:2]+a[2:]
>>> b
'ABC'
>>> id(b)
4429072688

For detailed explanation

Python 3.7

>>> a = 5
>>> id(a) 
4425034672
>>> b = 5
>>> id(b)
4425034672

Actually in python immutable objects (strings, integers, tuples) are stored in cache and it returns their location when we called id() function.

So, it returns same id for immutable objects as most the time they are cached in python as above.

For the same mutable objects id() returns different values.

Consider this example:

>>> d = { 'a' : 1 }
>>> id(d)
4426697136
>>> p = { 'a' : 1 }
>>> id(p)
4427492000

Note:

It may not return the same identity values for same immutable objects as they may/ may not be cached.