June 2017
Beginner
352 pages
8h 39m
English
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')>>> i3>>> 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 6, Exceptions .
Read now
Unlock full access