Pointers/References in Python?

Gary Herron gherron at islandtraining.com
Wed Jul 30 17:31:25 CEST 2008

boblatest at googlemail.com wrote:
> Hello,
> I have a long list of memory-heavy objects that I would like to access
> in differently sorted order. Let's say I'd like to have lists called
> by_date or by_size that I can use to access the objects in the
> specified order.
> Of course I can just build those lists naively by creating copies of
> the original list and then sorting them according to my wishes. But
> that would create huge memory overhead. Of course I could use lists of
> indices into the "master" list, just as in C I'd create lists or
> arrays of pointers into the original data.
> Is there a clever Python way to do this, or should I just use lists of
> indices?

No need.  A Python list contains *references* to objects, not copies of 
objects.  (The same is true of variables, dictionaries, sets, and so 

For example, in the following code,  only one copy of HeavyObject 
exists, however, it is referred to many times.

a = HeavyObject()
b = a
A = [a,b]
B = [b,a]
C = set([a,b])
D = {1:a, 2:b}
... and do on

Implementation wise, a long list consumes about 4 bytes per list element 
(that's one address per), plus a tine amount of overhead.

Gary Herron

> I know there is a thing called "shallow copy" that has something to do
> with not duplicating memory content but I don't understand the
> concept. Maybe that's what would help here, too.
> Thanks,
> robert
> --
> http://mail.python.org/mailman/listinfo/python-list

More information about the Python-list mailing list