MPKPAS
MPKPAS

Reputation: 3

Index duplicate values

I have a list, for instance list = [1,5,6,8,1,9]

I want the index of the smallest value, and after coding, it will show me 0 but the problem is the 1 is appearing twice. Can someone explain me how my program could show 4 instead of 0?

To make it clearer if I have a number k and my k is appearing x times in my list, I want that my program shows the index of the last k in the list (with k being the smallest value of the list).

Here is my code:

z=int(input())
a=0
y=[]
for loop in range(z):
    a=int(input())
    y.append(a)
print(y.index(min(y))+1)

Upvotes: 0

Views: 54

Answers (3)

uspectaculum
uspectaculum

Reputation: 402

def get_last_index(seq):
    return (len(seq)-1) - seq[::-1].index(min(seq))

Given:

lst = [1,5,6,8,1,9]

...

>>> lst = [1,5,6,8,1,9]
>>> get_last_index(lst)
4

The code simply reverses the list, retrieves the index of the item and takes that away from the total length of the list minus one for zero-indexability.

Upvotes: 2

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

This will get the last index of the smallest value.

lst = [1,5,6,8,1,9]
[c for c,e in enumerate(lst) if e==min(lst)][-1]

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

There could be better answer

[i for i,j in enumerate(list) if j==min(list)]
[0, 4]

Upvotes: 2

Related Questions