Search code examples
pythonlistloopselementthreshold

Returning the last element in a list larger than some threshold


Say we have the following list in Python:

[1,2,3,4,5,4,6,3,1,9,4,3,8,4,2,3,4,4,1,8]

How can we return the last element which is considered >=4?

I tried doing a for-loop and looking for the index, but felt that I went through some mess, apart from getting the unexpected result, and thought there might be an easier way to go about it.

Thanks.


Solution

  • Reverse lst with reversed, and call next.

    next(i for i in reversed(lst) if i >= 4)
    8
    

    This is efficient because it only iterates the minimum amount that it needs to, to return a result. This is equivalent to:

    for i in reversed(lst):
        if i >= 4:
            break
    
    print(i)
    8
    

    It so often happens that no element exists that meets your condition, and so next has nothing to return at all. In this case, next returns a StopIteration you can avoid by using calling the function with a default argument -

    next((i for i in reversed(lst) if i >= 4), None)
    

    Which returns None if no element meets the condition i >= 4.