Find index of item in list

S

Sean Berry

Given

myList = ['cat', 'dog', 'mouse' ... 'bear']

what is the easiest way to find out what index 'dog' is at?
 
S

Steven Bethard

wes said:
Sean said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top