python – Find minimum of a list ignoring zero values


I have a list of values ​​with zero elements and non-zero elements and I wanted to return the smallest value of the list and its index, but ignoring the zeros, that is, the fact that there are zeros does not mean that it is the smallest value but simply that it is not it is to be read.

So in a list like this: B=[6, 9, 4, 0, 7, 10, 2, 5, 0, 0, 0, 4, 11] I wanted it to return the value 2 and in this case the index 6.

I Tried to do:

for a in range(0,len(B)):
    if (B[a]!=0 and B[a]<B[a+1]):

But it doesn't give me what I want.

Someone can help me?


menorNumero = min(numero for numero in B if numero != 0)
indiceDoMenorNumero = B.index(menorNumero)

I'm applying the min function, which takes the smallest value from a list, to a generator expression (would also work with a list comprehension ). This expression can be read as "all non-zero numbers in list B".

The index function is used to get the position of the first occurrence of the number.

Scroll to Top