For example [1,2,3,4,1,2]
has min element 1, but it occurs for the last time at index 4.
>>> values = [1,2,3,4,1,2]
>>> -min((x, -i) for i, x in enumerate(values))[1]
4
No modification to the original list, works for arbitrary iterables, and only requires one pass.
This creates an iterable of tuples with the first value being the original element from the list, and the second element being the negated index. When finding the minimum in this iterable of tuples the values will be compared first and then the indices, so you will end up with a tuple of (min_value, lowest_negative_index). By taking the second element from this tuple and negating it again, you get the highest index of the minimum value.
Here is an alternative version that is very similar, but uses a key function for min()
:
>>> min(range(len(values)), key=lambda i: (values[i], -i))
4
Note that this version will only work for sequences (lists, tuples, strings etc.).
a = [1,2,3,4,1,2]
a.reverse()
print len(a) - a.index(min(a)) - 1
Update after comment:
The side effect can be removed by reversing again (but of course that is quite inefficient).
a.reverse()
len(list_) - list_[::-1].index(min(list_)) - 1
Get the length of the list, subtract from that the index of the min of the list in the reversed list, and then subtract 1.
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