list indexing

Christopher Koppler klapotec at chello.at
Thu Jul 31 16:21:53 EDT 2003


On 31 Jul 2003 12:53:09 -0700, ruach at chpc.utah.edu (Matthew) wrote:

>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.
>
>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.
>
>
>I know that I could do this
>
>list = ['this', 'is', 'a', 'list']
>counter = 0 
>for item in list:
>  if item = 'list':
>    print counter
>  else:
>    counter = counter + 1
>
>But is there an easier way?
>

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




More information about the Python-list mailing list