finding a value in a tuple

Chris Barker chrishbarker at home.net
Thu Nov 29 16:58:53 EST 2001


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

Actually, no. It is a "list". It would be a tuple if you had built it
like this:

mylist = ('one','two','three')

Parentheses rather than square brackets. The difference is that lists
are mutable (can be changed in place) and tuples care not.

> is there a way to run the php-like function in_array() on this.

Are you looking for "in"

>>> s = 'four'
>>> if s in mylist:
...     print s, " is in the list"
... else:
...     print s, " is not in the list"
...
four  is not in the list

> 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, it's not very Pythonic in a number of ways:

People do use dictionaries to simulate sets, but building it just for
this is kind of overkill.

If you are using a dict as a set, you can use the d.haskey() function,
rather than your try:except. 

if you do use a try: except, in general, it is better to catch just the
exception you are looking for:

>>> try:
...     d['four']
... except KeyError:
...     print "your value was not found"

Also, you don't need the if d['four']: in fact, I think is is a syntax
error, as there is no block inside the if..:

If "in" didn't exist the obvious (to me) way to do it would be:

>>> for i in mylist:
...     if i == 'four':
...             print "four is in the list"
...             break
... else:
...     print "four is not in the list"

The for...else... is a little wierd at first, but handy for this kind of
thing.

By the way, you might want to get on the Python tutor mailing list.
We're pretty helpful here, but a list designed for beginners may be more
useful:

http://mail.python.org/mailman/listinfo/tutor


-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list