[Tutor] searching for a value in an array (fwd)
Erik Price
erikprice@mac.com
Thu, 5 Sep 2002 17:18:17 -0400
On Thursday, September 5, 2002, at 04:20 PM, Danny Yoo wrote:
> ---------- Forwarded message ----------
> Date: Thu, 05 Sep 2002 19:21:40 +0000
> From: anthony polis <anthonypolis@hotmail.com>
> To: dyoo@hkn.eecs.berkeley.edu
> Subject: Re: [Tutor] searching for a value in an array
>
> Danny,
>
> Now I know how to search a list. But how do you pop() a list item
> without
> knowing it's location in the list? The Python tutorial told me I have
> to
> provide an integer in order to pop() an item out. How do I pop() an
> item
> out when I only know it's value?
This one's easy. You want the index() method of List objects:
>>> somelist = ['he-man', 'man-at-arms', 'skeletor', 'zoar']
>>> badguy = 'skeletor'
>>> num = somelist.index(badguy)
>>> popped = somelist.pop(num)
>>> popped
'skeletor'
>>> somelist
['he-man', 'man-at-arms', 'zoar']
>>>
I'm not sure what happens if there's more than one element in the list
that matches the argument to index. Let's find out:
>>> somelist
['he-man', 'man-at-arms', 'zoar']
>>> somelist.insert(2, badguy)
>>> somelist
['he-man', 'man-at-arms', 'skeletor', 'zoar']
>>> somelist.append('skeletor')
>>> somelist
['he-man', 'man-at-arms', 'skeletor', 'zoar', 'skeletor']
>>> somelist.pop(somelist.index(badguy))
'skeletor'
>>> somelist
['he-man', 'man-at-arms', 'zoar', 'skeletor']
>>>
Looks like it goes for the lowest-indexed element matching the argument
to index() but you might want to research this more.
Erik
--
Erik Price
email: erikprice@mac.com
jabber: erikprice@jabber.org