By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,842 Members | 2,186 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,842 IT Pros & Developers. It's quick & easy.

Find index of item in list

P: n/a
Given

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

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

Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Sean Berry wrote:
Given

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

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

Sean,
myList = ['cat', 'dog', 'mouse','bear']
myList.index('dog') 1


wes

Jul 18 '05 #2

P: n/a
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
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.