Removing objects

Patrick Mullen saluk64007 at gmail.com
Wed Jan 23 04:08:54 EST 2008


On Jan 22, 2008 10:59 PM,  <bladedpenguin at gmail.com> wrote:
> I am writing a game, and it must keep a list of objects. I've been
> representing this as a list, but I need an object to be able to remove
> itself. It doesn't know it's own index. If I tried to make each object
> keep track of it's own index, it would be invalidated when any object
> with a lower index was deleted.  The error was that when I called
> list.remove(self), it just removed the first thing in hte list with
> the same type as what I wanted, rather than the object I wanted. The
> objects have no identifying charachteristics, other than thier
> location in memory
>
> So my question: How do I look something up in a list by it's location
> in memory? does python even support pointers?
>
> Is there a better way?

To put it simply, list.remove(self) ought to work.  Are you sure it's
not working?  list.remove self doesn't delete the first matching type,
it deletes the first object that IS what you passed, or failing that,
it deletes the first object that == what you pass.

I use an idiom often in my games, where rather than deleting objects
on the fly, which is not very thread-safe in case you have something
scanning through the objects, I set a property .kill on objects that
are about to die, and then rebuild the list in the main loop with only
objects that haven't been killed.  I don't know if it's better, but it
would probably work in your situation if list.remove(self) isn't
working (which is strange).

The other benefit of my idiom, is that objects don't need to have a
reference to the object list, and any other function that wants to
delete that object needs no other references besides the object
itself.  I have trouble with references a lot in complex games, and
where I can I prefer not to have them.



More information about the Python-list mailing list