0

I am relatively new to Python, and have encountered this interesting case

We know that Python Index objects are Immutable, meaning we can not modify the each Index value. But consider the below example

data = DataFrame(np.arange(12).reshape((3, 4)),
                 index=['Ohio', 'Colorado', 'New york'],
                 columns=['one', 'two', 'three', 'four'])
print id(data.index),data.index
data.rename(index={'Ohio': 'INDIANA'}, inplace=True, columns={'three': 'peekaboo'})
print id(data.index), data.index

Out:

133636144 Index([u'Ohio', u'Colorado', u'New york'], dtype='object')
133636144 Index([u'INDIANA', u'Colorado', u'New york'], dtype='object')

Here, we observe that the Index object is actually Mutable, since in the 2 print statements, the id of data.index is the same(pointing to the same Index Object), but the values are different. This is only possible if the Index is Mutable.

How come there is this inconsistency? In this case they are Mutable, but immutable otherwise

Update:

Few comments below have pointed out similarities with the Why is the id of a Python class not unique when called quickly? question.

But I tried with this code, I intended to save the index ID information in a list. Executing the query ...

data = DataFrame(np.arange(12).reshape((3, 4)),
index=['Ohio', 'Colorado', 'New york'],
columns=['one', 'two', 'three', 'four'])
x = []
x.append(id(data))
x.append(data.index)
data.rename(index={'Ohio': 'INDIANA'}, inplace=True,columns={'three':                      'peekaboo'})
print id(data),data.index
print x[0],x[1]

Gives the same output

135289936 Index([u'INDIANA', u'Colorado', u'New york'], dtype='object')
135289936 Index([u'Ohio', u'Colorado', u'New york'], dtype='object')

Is not it like this: Garbage collector can not destroy data, as its information is still saved in the list. In other words, Does not this mean, the data object was not destroyed, as the first element of the list still points to the ID

Community
  • 1
  • 1
Shivanand T
  • 1,093
  • 1
  • 10
  • 18
  • 3
    No, it just means a memory location was reused http://stackoverflow.com/questions/35173479/why-do-different-methods-of-same-object-have-the-same-id/35173613#35173613 – Padraic Cunningham Mar 21 '16 at 00:04

1 Answers1

0

Based on the documentation of id():

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

If one object is garbage-collected, its id (aka memory address) can be recycled for a new object.

Community
  • 1
  • 1
Patrick the Cat
  • 2,138
  • 1
  • 16
  • 33