finding a value in a tuple

Garth Grimm garth_grimm at hp.com
Thu Nov 29 22:35:34 CET 2001


Dan Allen wrote:

> Say I have
> 
> mylist = ['one','two','three']
> 
> which I presume is a "tuple" as I have been scanning the manual. 


That's a list, not a tuple.  A tuple would be like myTuple = { 'one', 'two', 'three' )

> Now,
> is there a way to run the php-like function in_array() on this. 
> Consider this, I want to know if one of the values in that tuple is
> exactly equal to "four".  The answer of course is no, but how would I
> find it.  Here is what I have so far, which works, but it is ugly..


This should work...

if value in mylist: doStuffHere
else: doOtherStuff

or

if value not in mylist: doStuffHere
else: doOtherStuff

They should work for both tuples, and lists, (and strings too, I think)

Or, you could do list specific things, like:

if mylist.count(value) > 0 :

or just call mylist.index(value) and catch the exception that's raised if the value isn't in the list,

or there is probably some other ways, but one of the ones above should be adequat.

Garth


> 
> d = {}
> for value in mylist
>   d[value] = 1
> try:
>   if d['four']:
>     print "your value was found"
> except:
>   print "your value was not found"
> 


Okay, d = {} is a dictionary, not a list nor a tuple.

In this case, use something like

if d.has_key(value): doStuffHere
else: doOtherStuff

what you're trying to do above is access a key-value pair, and then handling the exception raised if 
the key doesn't exist.  That also works, but don't use a dictionary unless you actually have 
key-value pairs.

Garth


> Two question here, is that a bad use of try/except?  Second is, is
> there an array_flip, or do you just have to do what I did above?  I
> would imagine there is a way to search down the tuple.
> 
> Thanks!
> 
> Dan
> 




More information about the Python-list mailing list