The in opperator -- How do I use it?

Alex Martelli aleaxit at yahoo.com
Wed Mar 7 02:56:28 EST 2001


"Brad Bollenbach" <bbollenbach at homenospam.com> wrote in message
news:dTkp6.13293$hn5.1934677 at news1.rdc1.mb.home.com...
> Think of the "in" operator as the list membership operator...because
that's
> what it is. :)

Slightly more general than that -- it's a membership operator
(not just in lists, but, rather, in all kinds of sequences,
user-defined instance objects that define a __contains__
method, and maybe one day in mappings as well, though I think
that addition was retracted for Python 2.1).


For example, module string contains an attribute, named
'letters', which is a string made up of all the letters.
You can test any single character for membership in that
string, using the in operator:

>>> import string
>>> if 'a' in string.letters: print 'a is a letter'
...
a is a letter
>>> if '3' not in string.letters: print '3 is not a letter'
...
3 is not a letter
>>>


Of course, that may not be optimal, since the .isalpha
string method does the same job, probably faster:

>>> 'a'.isalpha()
1
>>> '3'.isalpha()
0
>>>

...but it may come in handy for testing membership into
any short runtime-computed string -- you don't have to
make it into a list to be able to apply the in operator.


Alex






More information about the Python-list mailing list