The in opperator -- How do I use it?

Alex Martelli aleaxit at
Wed Mar 7 08:56:28 CET 2001

"Brad Bollenbach" <bbollenbach at> wrote in message
news:dTkp6.13293$hn5.1934677 at
> Think of the "in" operator as the list membership operator...because
> 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()
>>> '3'.isalpha()

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


More information about the Python-list mailing list