[Tutor] >> BANANAS! << Removing a class instance from a list?

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 6 Mar 2001 08:39:47 -0800 (PST)


On Tue, 6 Mar 2001, Chris McCormick wrote:

> So far, so good, right?  It's easy to append to the list.  The problem
> comes when I try to remove items from the list.  I'm supposed to use
> the value of the item I want to remove.  But what is the value of a
> class instance?  If I create two bananas and then print my list, I get
> something like this:
> 
> [<flora.banana instance at 0081168C>, <flora.banana
> instance at 0081144C>]
> 
> How do I feed that into banana.remove(listitemvalue)?

It depends on the situation.  Which kind of banana do you want to remove?  
If it depends on the position (for example, the last banana), we don't
need to use remove(): we can use del instead:

    del(bananas[-1])

will remove the last banana from our bananas.  Yum.

remove()'s useful when we do have a value to remove.  For example:

###
for b in bananas:
    if overripe(b):
        badbanana = b
bananas.remove(badbanana)
###

should get rid of the very last banana we see in the for loop.  If you can
tell us the criteria of a banana you want to remove, we can point you
toward the appropriate removing function.

If we want to look at the other list functions, we can do this:
###
>>> print dir(bananas)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
###

Not only can we remove bananas, but we can pop() them too!  (This is
beginning to sound weird.  *grin*)  pop() takes in the position of a
banana in a list, and returns that particular value:

###
>>> numbers = range(5)
>>> numbers
[0, 1, 2, 3, 4]
>>> numbers.pop(0)
0
>>> numbers
[1, 2, 3, 4]
>>> numbers.pop(-1)
4
>>> numbers
[1, 2, 3]
###

and this might be useful for you.


By the way, what you're looking at,

> [<flora.banana instance at 0081168C>, <flora.banana instance at
> 0081144C>]

is the string representation of the list elements, and it doesn't look too
pretty yet.  An object might not have an immediately meaningful
representation as a string, but Python tries hard to make one up.  When
Python tries to print out a list of elements, it calls the repr()
"representation" function on each element of the list.  If we want our
representation to look nicer, we can write our own __repr__() function for
bananas.

The reference manual talks about these sort of special functions here:

    http://python.org/doc/current/ref/specialnames.html


> Thanks in advance for your help.  We're being overrun here.

Don't go bananas.