Position in an list?
you can use ['hello', 'world'].index('world')
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"
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