list indexing

Sean Ross sross at connectmail.carleton.ca
Thu Jul 31 17:15:26 EDT 2003


"Matthew" <ruach at chpc.utah.edu> wrote in message
news:ec1162c7.0307311153.26d1b999 at posting.google.com...
> Hello, I am rather new to python and I have come across a problem that
> I can not find an answer to any where I my books. What I would like to
> know is if there is a way to get the index number of a list element by
> name. Sort of the inverse of the .index() method.

Perhaps I've misunderstood, but it looks like you want:
>>> words = ['this', 'is', 'a', 'list']
>>> words.index('list')
3

which is, of course, not the inverse of .index() (but .index() itself).

In general, if you use this, you'll either need to be certain that the item
is indeed in the list, or nest the call in a try/except like so:
>>> try:
...  index = words.index('list')
... except ValueError:
...  pass     # or whatever you want to do when the look-up fails
...
>>> index
3

HTH
Sean






More information about the Python-list mailing list