Finding list elements with index()

To find an element in a list, use the index() method passing the object you're searching for. The elements are compared for equivalence until the one you're looking for is found:

>>> w = "the quick brown fox jumps over the lazy dog".split()
>>> w
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> i = w.index('fox')
>>> i
3
>>> w[i]
'fox'

If you search for a value that isn't present, you receive a ValueError:

>>> w.index('unicorn')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'unicorn' is not in list

We'll learn how to handle such errors gracefully in chapter 6Exceptions .

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset