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

Kalle Svensson kalle@gnupung.net
Tue, 6 Mar 2001 18:09:43 +0100


[not signed due to technical difficulties]

Sez Chris McCormick:
> 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)?

>>> class Banana:
...   def __init__(self, n):
...     self.name = n
... 
>>> a = Banana("adam")
>>> b = Banana("bill")
>>> c = Banana("cliff")
>>> bananas = [a, b, c]
>>> bananas
[<__main__.Banana instance at 8057008>, <__main__.Banana instance at
804b4e0>, <__main__.Banana instance at 8056e58>]
>>> bananas.remove(b)
>>> bananas
[<__main__.Banana instance at 8057008>, <__main__.Banana instance at 8056e58>]

All right.  But you want to ask the user what bananas to remove?

Either ask for a number:
>>> i = input("Which banana shall I remove? (1-%d) " % len(bananas))
Which banana shall I remove? (1-2) 2
>>> del bananas[i-1] # -1 for offset
>>> bananas
[<__main__.Banana instance at 8057008>]

Or a name (or something else that can be used to separate bananas):
>>> s = raw_input("What banana do you want to delete? ")
What banana do you want to delete? adam
>>> for banana in bananas:
...   if banana.name == s:
...     bananas.remove(banana)
... 
>>> bananas
[]

HTH,
  Kalle
-- 
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD