Welcome, guest | Sign In | My Account | Store | Cart

Oftentimes you want to find the index of a list-like object. Numpy arrays, for example, do not have a index member function. These get the job done quickly.

Note: these do not raise exceptions, instead they return -1 on error. You should change that if you want different behavior.

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def first_index_gt(data_list, value):
    '''return the first index greater than value from a given list like object'''
    try:
        index = next(data[0] for data in enumerate(data_list) if data[1] > value)
        return index
    except StopIteration: return - 1

def first_index_lt(data_list, value):
    '''return the first index less than value from a given list like object'''
    try:
        index = next(data[0] for data in enumerate(data_list) if data[1] < value)
        return index
    except StopIteration: return - 1

def first_index_ne(data_list, value):
    '''returns first index not equal to the value from list'''
    try:
        index = next(data[0] for data in enumerate(data_list) if data[1] != value)
        return index
    except StopIteration: return - 1

def first_index_et(data_list, value):
    '''same as data_list.index(value), except with exception handling
    Also finds 'nan' values'''
    try:
        if type(value) == float and math.isnan(value):
            return next(data[0] for data in enumerate(data_list)
              if (type(data[1]) in (float, np.float64, np.float32, np.float96)
              and math.isnan(data[1])))
        else:
            return next(data[0] for data in enumerate(data_list) if data[1] == value)
    except (ValueError, StopIteration): return - 1
Created by Garrett on Tue, 13 Mar 2012 (MIT)
Python recipes (4591)
Garrett's recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks