list indexing

Matthew ruach at chpc.utah.edu
Fri Aug 1 16:50:12 EDT 2003


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

Christopher Koppler <klapotec at chello.at> wrote in message news:<76uiivkl7vlr98ggp1p7i4h8m8h2s0sbs0 at 4ax.com>...
> Using a recent Python you can use enumerate (built-in):
> 
> list = ['this', 'is', 'a', 'list']
> for cnt, item in enumerate(list):
> 	if item == 'list':
> 		print cnt
> 
> 
> 
> --Christopher

Mark Day <mday at apple.com> wrote in message news:<310720031327225125%mday at apple.com>...
> 
> If you're using Python 2.3, you can use enumerate() like this:
> 
> for index,item in enumerate(list):
>     if item == 'list':
>         print index
> 
> BTW: I'd suggest not using the name of a built-in class for your
> variable "list".  Perhaps "mylist" or "words"?
> 
> -Mark



Thanks Sean (& Mark and Christopher)
You were right I misunderstoof the use of index(). It does do exactly
what I want. However Mark and Christophers replies better suit this
particular problem.

Thanks very much All
-matthew




More information about the Python-list mailing list