1

I'm doing a simple lookup

if xo.st in sts:
    #...

If the condition is met I need to get the index of the element in sts (sts is a list or a tuple). This needs to be fast (it is a big list). What is the best solution for this?

LarsVegas
  • 6,522
  • 10
  • 43
  • 67

4 Answers4

4

What about:

if xo.st in sts:
    print sts.index(xo.st)

This will return the first index of xo.st insts

  • 1
    This solution will search the list two times: once to see if the item is in the list, and then a second time to get its instance! Better to just do `index()` and catch the `ValueError` as shown in Victor's solution. This will only search the list once. – kindall Aug 01 '13 at 16:45
3

First thing that comes to mind is

list.index(xo.st) 
Pawel Miech
  • 7,742
  • 4
  • 36
  • 57
3

list and tuple both have an index method, which returns the index for a value if it's in the data, or raises a ValueError if it's not present.
If you want speed you might want to keep an ordered list and do a binary search Here is a previous SO about this.

Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
2

The index method, present in lists and tuples, is what you need. It raises a ValueError when the value is NOT in the list. If that's not what you want, you can make something like this:

>>> def get_index(value, sequence):
...     try:
...         return sequence.index(value)
...     except ValueError:
...         return None
... 
>>> l = [1,2,3,4,5]
>>> print get_index(1, l)
0
>>> print get_index(2, l)
1
>>> print get_index(9, l)
None
Victor Silva
  • 564
  • 4
  • 13
  • 2
    Uh, `[1,2,3,4,5][-1]` will yield 5 in this case. I think you might want to return `None` instead of -1. –  Aug 01 '13 at 14:25