Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The free list for lists seems to reuse more than just empty lists as you suggest.

  > a = ['non','empty','list']
  > id(a)
  4363176072
  > del a
  > b = ['new', 'list']
  > id(b)
  4363176072


Maybe I've missed something, but you can also get the same id (it's basically an address in the memory) because of the how memory allocation works. There is a special allocator in CPython, which preallocates big chunks of memory and constantly reusing it without allocation overhead. I have an article on this too.


Ahh.. interesting. Then I guess using the id of the tuples to show that they are using the same object doesn't exactly prove the point.

To your original point (that tuples reallocate based on length) I see that if I delete a tuple of length 3 and then create a tuple of length 5 I see the id is immediately changed. So that's correct.

Lists on the other hand seem to keep reallocating the same address in my limited test.

Strings seem to behave like tuples. When I delete a string and create a new one it creates a new object with a new address.... unless the strings are of the same length.

Perhaps this is no real revelation, I'm rather new to python and spending my time poking around to see how it works. :)


> Then I guess using the id of the tuples to show that they are using the same object doesn't exactly prove the point

Without the `del a`, it does, because they both have active references. If they were unique objects, we'd see a unique ID for `b` as long as a reference to `a` is active.

> Strings seem to behave like tuples. When I delete a string and create a new one it creates a new object with a new address.... unless the strings are of the same length.

String _objects_ (as opposed to variables referring to them) are immutable in Python. They tend to be allocated anew, but for optimization reasons you can end up with cases where the string objects have the same ID. Like here:

>>> a = 'asdf' >>> id(a) 4389881424 >>> a = 'qwerty' >>> id(a) 4395015672 >>> a = 'asdf' >>> id(a) 4389881424

'asdf' has the same ID with no deling involved because its object wasn't GC'd yet.

Below are some relevant links if you want to knock yourself out (some do) but I write an awful lot of Python and even for me this is well into the realm of "what happens when..." after a few beers or job interview trivia.

https://rushter.com/blog/python-lists-and-tuples/ http://guilload.com/python-string-interning/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: