What would be the most Pythonic way to find the first index in a list that is greater than x?
For example, with
list = [0.5, 0.3, 0.9, 0.8]
The function
f(list, 0.7)
would return
2.
The Python list. index() method returns the index of the item specified in the list. The method will return only the first instance of that item.
In any list the first element is assigned index value 0 and the last element can be considered as a value -1.
Index in a list starts with 0. This essentially means that the first element in the list has an index of 0 and not 1 and subsequently the second element has an index of 1. This concept holds true for most programming languages.
As discussed earlier, the index() in Python returns the position of the element in the specified list or the characters in the string. It follows the same syntax whether you use it on a list or a string. The reason being that a string in Python is considered as a list of characters starting from the index 0.
next(x[0] for x in enumerate(L) if x[1] > 0.7)
if list is sorted then bisect.bisect_left(alist, value)
is faster for a large list than next(i for i, x in enumerate(alist) if x >= value)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With