list indexing

Mark Day mday at apple.com
Thu Jul 31 16:27:22 EDT 2003


In article <ec1162c7.0307311153.26d1b999 at posting.google.com>, Matthew
<ruach at chpc.utah.edu> wrote:

> 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.
> 
> For example
> 
> list = ['this', 'is', 'a', 'list']
> for item in list:
>   if item = 'list':
>     print ????
> 
> 
> ???? Is where I want to be able to get the index number, in this case
> 3 from the list in a simple fasion.

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




More information about the Python-list mailing list