arsenal88
arsenal88

Reputation: 1160

Finding last element index based on condition

I have a list of strings, e.g.

lst = ['2', '\n', '4', '\n', '\n']

I'm trying to determine the index point of the last string element that is not '\n'. In the above example the index point would be 2 as '4' is the last element whose value is not '\n'.

I can find the first occurance of '\n' easy etc:

lst.index('\n') 

Is there a way to find the last occurance of an element that IS NOT of a particular string char?

Upvotes: 4

Views: 2289

Answers (1)

jpp
jpp

Reputation: 164673

You can use next with enumerate, then subtract the result from the length of your list:

lst = ['2', '\n', '4', '\n', '\n']
idx = len(lst) - next(i for i, val in enumerate(reversed(lst), 1) if val != '\n')  # 2

Or, as proposed by @Chris_Rands, iterate backwards via a range that counts down:

idx = next(i for i in range(len(lst)-1, -1, -1) if lst[i] != '\n')  # 2

Upvotes: 5

Related Questions