Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Python list index greater than x?

Tags:

python

list

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. 
like image 785
c00kiemonster Avatar asked Feb 10 '10 13:02

c00kiemonster


People also ask

How do I get the first index of a list in Python?

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.

What is the index value of the first item on a list Python?

In any list the first element is assigned index value 0 and the last element can be considered as a value -1.

What is the index of the first item in a list?

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.

What does index [] do in Python?

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.


2 Answers

next(x[0] for x in enumerate(L) if x[1] > 0.7) 
like image 200
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 13:11

Ignacio Vazquez-Abrams


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).

like image 20
jfs Avatar answered Nov 15 '22 14:11

jfs