[Tutor] The In Operator

John Fouhy john at fouhy.net
Thu Jul 27 05:38:55 CEST 2006


On 27/07/06, Steve Haley <sfhaley at gmail.com> wrote:
> The error message is the same when I run the author's code but the error
> statement itself seems to indicate that there IS an in operator.  I guess I
> really have a three questions.  Is the in operator in version 2.1 of Python?
>  If it is, what is the syntax?  (I tried to find it in the help etc. and
> couldn't.)

There is an 'in' operator in py2.1; as the error message explains, it
expects a sequence on the right hand side.

Sequences are:
 - lists
 - strings
 - tuples

You could change the code to:

     if "Dancing Baloney" in geek.keys():

and it would work; the .keys() method of a dictionary returns a list
containing the dictionary's keys (in arbitrary order).

You could also change the code to:

    if geek.has_key("Dancing Baloney"):

This will be more efficient, and this is equivalent to using "in" in
recent versionf of python.
(ie: "key in dict" is equivalent to "dict.has_key(key)")

(are you new to programming in general, or just python in particular?)

-- 
John.


More information about the Tutor mailing list