finding a value in a tuple

Chris Liechti cliechti at gmx.net
Thu Nov 29 22:16:46 CET 2001


[posted and mailed]

bigredlinux at yahoo.com (Dan Allen) wrote in 
news:28d73ad6.0111291249.6fb9b6eb at posting.google.com:

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

no thats a list. a tuple is is that:
mytuple = ('one','two','three')

the tuple can not be change, but a list can be changed.


> 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..
> 
> d = {}
> for value in mylist
>   d[value] = 1
> try:
>   if d['four']:
>     print "your value was found"
> except:
>   print "your value was not found"

well thats a very long way to it... just type

if 'four' in mylist:
    	print "found"


> Two question here, is that a bad use of try/except?  Second is, is

no, but you should specify the exception, otherwise you'll catch other 
exceptions that have nothing to do with the existence of a key too.

except KeyError:
    	...

in this case there is a solution without exceptions too:

if d.has_key('four'):
    	print "found"

> 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.

as sayed above use "in"

chris

> 
> Thanks!
> 
> Dan
> 



-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list