Python: finding an element in a list


Question

What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.

Is there a way to specify what comparison operator to use?

1
144
11/15/2018 4:51:04 PM

Accepted Answer

The best way is probably to use the list method .index.

For the objects in the list, you can do something like:

def __eq__(self, other):
    return self.Value == other.Value

with any special processing you need.

You can also use a for/in statement with enumerate(arr)

Example of finding the index of an item that has value > 100.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

50
9/1/2018 4:51:30 PM

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon