On Thu, Jan 7, 2010 at 5:58 PM, Anand Chitipothu <anandol...@gmail.com>wrote:
> On Thu, Jan 7, 2010 at 1:44 PM, leela vadlamudi > <leela.vadlam...@gmail.com> wrote: > > Hi, > > > > Python docs says that id function returns the unique id for an object. > > > >>>> id(10) > > 165936452 > >>>> a=10 > >>>> id(a) > > 165936452 > >>>> b = int(10) > >>>> id(b) > > 165936452 > > > >>>> x = tuple() > >>>> y=tuple() > >>>> id(x) > > -1208311764 > >>>> id(y) > > -1208311764 > > > >>>> l = list() > >>>> m = list() > >>>> id(l) > > -1210839956 > >>>> id(m) > > -1210839700 > > > > >From the above example, id(mutable_object) returns different ids, but > > id(immutable_object) return always the same id. If I try to create new > > immutable object, It is just returning the existed object instead of > > creating new. How does it internally manages to return the same object? > Why > > it is not creating new object if it is immutable? > > > > What about this below case? > > > >>>> id((1,)) > > -1208770004 > >>>> id((1,)) > > -1208770004 > >>>> a=(1,) > >>>> id(a) > > -1208745460 > >>>> id((1,)) > > -1208759028 > > > > Why is id changes here even if it is a tuple(immutable) > > Most of the times id function returns the memory location used by that > object. In most of your examples, the tuple was getting allocated > again at the same location. > > >>> id((1, 2, 3)) > 601544 > >>> id((1, 2, 3)) > 601544 > >>> id((1, 2, 33)) > 601544 > >>> id((1, 2, 42)) > 601544 > > Notice that it is returning the same id even if the contents of tuple > are different. Same thing works for lists too. Immutability doesn't > really matter. > > Looks like immutability matters ... >>> a = [() for i in range(4)] >>> for i in a: ... print id(i) ... -1208311764 -1208311764 -1208311764 -1208311764 >>> b = [[] for i in range(4)] >>> for i in b: ... print id(i) ... -1208446612 -1208446516 -1208446644 -1208446196 >>> It is not creating multiple tuple objects, giving the same id to all tuples. But It's not same with lists. > >>> id([1, 2, 3]) > 601584 > >>> id([1, 2, 3]) > 601584 > >>> id([1, 2, 3]) > 601584 > >>> id([1, 2, 33]) > 601584 > >>> id([1, 2, 42]) > 601584 > > But try allocating some between these calls and the id changes. > > >>> id((1, 2, 3)) > 601544 > >>> a = (1, 2, 3) > >>> id((1, 2, 3)) > 628096 > >>> > >>> id([1, 2, 3]) > 601584 > >>> x = [1, 2, 3] > >>> id([1, 2, 3]) > 598544 > _______________________________________________ BangPypers mailing list BangPypers@python.org http://mail.python.org/mailman/listinfo/bangpypers