Reputation: 21
a = [2, 2, 4, 2, 5, 7]
If one is to find the minimum value in this list (which is 2
) the corresponding indexes of 2
in the list a
are 0, 1 and 3 respectively.
How to tell python to use the minimum value at the highest index (the number 2
at index 3)?
Upvotes: 2
Views: 617
Reputation: 644
Try this:
a=[2,2,4,2,5,7]
minval=min(a) #min of a
for l in range(len(a)):
if a[l]==minval:
index=l
continue
print index
Upvotes: 0
Reputation: 22964
You can simply reverse the list using a[::-1]
and then apply the same technique to find the index. a[::-1].index(min(a))
will give us the index of minimum value from the end, in order to record the index w.r.t to 0th position(starting of list) we can subtract a[::-1].index(min(a))
from len(a) - 1
.
a = [2, 2, 4, 2, 5, 7]
print len(a) - a[::-1].index(min(a)) - 1
>>> 3
Upvotes: 4
Reputation: 19050
This can be written as a function indexes()
and then take the max()
of the resulting iterator:
Example:
def indexes(xs, value):
for i, x in enumerate(xs):
if x == value:
yield i
a = [2, 2, 4, 2, 5, 7]
print max(indexes(a, min(a))) # 3
Update; Just as a matter of completeness; if you per se wanted the minimum index for a set of values with more than one minimum you'd just swap out max()
for min()
at the front of the expression. So:
a = [2, 2, 1, 4, 2, 1, 5, 7]
print min(indexes(a, min(a))) # 2
whilst:
print max(indexes(a, min(a))) # 5
This is kind of handy and flexible in general :)
Upvotes: 2
Reputation: 40843
Find the smallest, then iterate over the list collecting the indices of the matching values.
smallest = min(items)
indices = [index for index, value in enumerate(items) if value == smallest]
largest_index = max(indices) # or indices[-1]
If you have a very long list then you might want to start from the back and stop once you reach the first item.
largest_index = len(items) - next(index for index, value in \
enumerate(reversed(items), start=1) if value == smallest)
Upvotes: 0
Reputation: 180512
use enumerate reversing the list with a start index of 1
calling next in the generator to get the first value, subtracting the index from the length of the list.
a = [2, 2, 3, 2, 5, 7]
mn = min(a)
print(len(a) - next(i for i, ele in enumerate(reversed(a),1) if ele == mn))
3
Upvotes: 2
Reputation: 16154
Iterate through the enumerated list and use the maximum index :
In [109]: max([ind for ind, val in enumerate(a) if val==min(a)])
Out[109]: 3
Upvotes: 0