Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position in an list?

I will check if a word exists in a list. How can I show the position of this word?

like image 553
kame Avatar asked Nov 02 '10 20:11

kame


2 Answers

list = ["word1", "word2", "word3"]
try:
   print list.index("word1")
except ValueError:
   print "word1 not in list."

This piece of code will print 0, because that's the index of the first occurrence of "word1"

like image 197
Gabi Purcaru Avatar answered Nov 19 '22 01:11

Gabi Purcaru


To check if an object is in a list, use the in operator:

>>> words = ['a', 'list', 'of', 'words']
>>> 'of' in words
True
>>> 'eggs' in words
False

Use the index method of a list to find out where in the list, but be prepared to handle the exception:

>>> words.index('of')
2
>>> words.index('eggs')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'eggs' is not in list
like image 3
Josh Lee Avatar answered Nov 19 '22 02:11

Josh Lee