List Element without iteration

The mylist.index("blah") method of a list will return the index of the first occurrence of the item “blah”:

>>> ["item 1", "blah", "item 3"].index("blah")
1
>>> ["item 1", "item 2", "blah"].index("blah")
2

It will raise ValueError if it cannot be found:

>>> ["item 1", "item 2", "item 3"].index("not found")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

You can also use the in keyword to determine if an item is in a list (but not the location):

>>> "not found" in ["item 1", "blah", "item 3"]
False
>>> "item 3" in ["item 1", "blah", "item 3"]
True

As Harper Shelby commented, Python will still have to iterate internally to find the items, but the index or in methods may be slightly quicker than doing it in Python, as the data-structures are implemented in C.. but more importantly,

"x" in mylist

..is much tidier than..

found = False
for cur in mylist:
    if cur == "x":
        found = True

Leave a Comment