Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the index of the first coincidence in a list giving a starting position but backward

Tags:

python

Is there any pythonic way to find the first coincidence before a giving index?

For example I want to find the 2 that go before the 1, and the the 2 that go after the 1.

a = [0,2,0,0,1,0,0,2,0]

for the 2 that go after the 1 I use this a.index(2,4).

Is there any easy or clean way to do it?

like image 493
exsnake Avatar asked Mar 05 '23 18:03

exsnake


2 Answers

You can reverse the list and calculate the index of your "pivot" element in the reversed list, then use index as normal:

def find_before(lst, e, idx):
    new_idx = len(lst) - idx - 1
    return len(lst) - lst[::-1].index(e, new_idx) - 1

It's worth noting that this is a bad idea for huge lists because it temporarily creates a copy when it reverses it. A better idea for that scenario is what blhsing did, which is just stepping backwards through the list:

def find_before(lst, e, idx):
    i = idx
    while i > 0:
        i -= 1
        if lst[i] == e:
        return i
    else:
        raise ValueError(f"No element {e} found before index {idx}")
like image 130
MoxieBall Avatar answered Mar 13 '23 07:03

MoxieBall


You just have to do it yourself since there's no built-in function for the equivalent of str.rindex for lists:

def rindex(lst, x, start=-1, end=0):
    if start < 0:
        start += len(lst)
    i = start
    while i >= end and lst[i] != x:
        i -= 1
    if i < 0:
        raise ValueError()
    return i

a = [0,2,0,0,1,0,0,2,0]
print(rindex(a, 2, 4))

This outputs:

1
like image 45
blhsing Avatar answered Mar 13 '23 07:03

blhsing