0

Imagine I have a list

l = [12,13,14,10,13,14]

and I want to find the index from which on all items are greater than 10 (in this case it is the index 4 corresponding to 13 as the first occurence of this property).

Maybe based on this, how to do this best with Python?

my idea: create a bool list for this [a>10 for a in l] (which consists of True and False as sequence) , alternatively l>10 yields an array somehow using numpy?

pas-calc
  • 115
  • 9

5 Answers5

0

You can iterate backwards through the list and catch the index of the first condition failure. This prevents issues where several values fail...

In [51]: l                                                                                  
Out[51]: [12, 13, 14, 10, 13, 14]

In [52]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
Out[52]: 4

In [53]: l = [12, 13, 10, 20, 10, 15]                                                       

In [54]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
Out[54]: 5

In [55]: l = [23, 55]                                                                       

In [56]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         

In [57]: 

 
AirSquid
  • 10,214
  • 2
  • 7
  • 31
0
l = [12,13,14,10,13,14]
i = len(l)
for i in reversed(l):
    condition = v > 10
    if not condition:
        break
    i -= 1
print(i)
# Output : 4

Be careful with the case of the last element of the list not satisfying the condition. The i value would be equal to len(l) wich is not a valid index for the list. It is up to you to choose how to manage that special case.

Niko B
  • 751
  • 5
  • 9
0

You can start from end of the array :

def findStartOfMoreThan(l,limit):
    for i in range(len(l)-1, -1, -1):
        if l[i]<=limit :
            return i+1
    return (-1)
    
assert(findStartOfMoreThan([12,13,14,10,13,14],10) == 4)
assert(findStartOfMoreThan([12,13,14,10,13,14,15],10)==4)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],10)==5)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],13)==6)
Zerty91
  • 1
  • 2
0

Simplest solution is to negate the condition to get the last index that has element <=10 using

l = np.array([12,13,14,10,13,14])
first_index = np.where(l<=10)[0][-1]+1 # yields the first index that satisfies the condition

One could first check for len(np.where(...)) to verify that the condition is violated at least once, else return 0 for first index.

pas-calc
  • 115
  • 9
-1

Here you go:

[l.index(item) for item in l if not item>10][-1]+1
Shady
  • 216
  • 2
  • 6