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?
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?
What about:
if xo.st in sts:
print sts.index(xo.st)
This will return the first index of xo.st
insts
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.
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