I will check if a word exists in a list. How can I show the position of this word?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With