list indexing

Peter Abel p-abel at t-online.de
Fri Aug 1 15:38:42 EDT 2003


"Sean Ross" <sross at connectmail.carleton.ca> wrote in message news:<OGfWa.8894$Cx4.875868 at news20.bellglobal.com>...
> "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

And if 'list' would appear more than once,
the following could help:
>>> words = ['this', 'is', 'a', 'list','and','this','is','a','list','too']
>>> for i in range(len(words)):
... 	if words[i]=='list':
... 		print i
... 
3
8

Regards,
Peter




More information about the Python-list mailing list