Find index of item in list
Steven Bethard
steven.bethard at gmail.com
Tue Dec 7 15:07:47 EST 2004
wes weston wrote:
> Sean Berry wrote:
>
>> myList = ['cat', 'dog', 'mouse' ... 'bear']
>>
>> what is the easiest way to find out what index 'dog' is at?
>
> >>> myList = ['cat', 'dog', 'mouse','bear']
> >>> myList.index('dog')
> 1
> >>>
Yup, list.index is almost certainly what you want, though it's worth
mentioning that list.index returns the *first* occurrence of the item in
the list. You can get later items by supplying an appropriate starting
index:
>>> my_list = ['cat', 'dog', 'mouse', 'bear', 'dog']
>>> my_list.index('dog')
1
>>> my_list.index('dog', 2)
4
>>> my_list.index('dog', 5)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
Steve
More information about the Python-list
mailing list