Finding the index of an item given a list containing it in Pythonpython


One thing that is really helpful in learning Python is to use the interactive help function:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)

 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value

which will often lead you to the method you are looking for.


For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?

Python: finding an element in an array

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


If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
>>> 'damn' in li

I think you can do it by this

TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
   print TupList.index(i)