How to evaluate the index of the last in a list surpassed by a comparison date?

I have objects stored in a list and would like to get the index of the last before a comparison stored in a variable. In the example below, the last object surpassed by the comparison date would be, 2, 1) with an index of 2.

I have working code but it seems quite convoluted. I use a function (taken from here) to get a list of the index numbers of all dates occuring before the comparison date, then getting the value of the last index in this list. A simpler approach would be most welcome.

import datetime

def get_index(list_of_elems, condition):
    index_pos_list = []
    for i in range(len(list_of_elems)):
        if condition(list_of_elems[i]) == True:
    return index_pos_list

dates = [, 2, 1),, 2, 1),, 2, 1),, 2, 1),, 2, 1),, 2, 1)]

comparison_date =, 11, 5)

index_pos_list = get_index(dates, lambda x : x < comparison_date)

last_index = len(index_pos_list) - 1

>Solution :

Since you only need to get the last index of a date before the comparison date, I’d suggest creating a separate function get_last_index which does exactly that.

Also, in this case it’s better to iterate over the list in reverse order, so that we can just return the first encountered index where the condition matches as true.

def get_last_index(list_of_elems, condition) -> int:
    for i in range(len(list_of_elems) -1, -1, -1):
        if condition(list_of_elems[i]):
            return i
    # no date earlier than comparison date is found
    return -1

last_index = get_last_index(dates, lambda x: x < comparison_date)




Note that the function could also be rewritten to use a generator expression, with next to get the first result of the expression:

def get_last_index(list_of_elems, condition, default_idx=-1) -> int:
        return next(i for i in range(len(list_of_elems) - 1, -1, -1)
                    if condition(list_of_elems[i]))
    except StopIteration:  # no date earlier than comparison date is found
        return default_idx

Leave a Reply