How to find the smallest positive value in a list in python

Active May 26, 2020    /    Viewed 16000    /    Comments 0    /    Edit


Examples of how to find the smallest positive value in a list in python ?

1 -- Find the minimum value

Let's consider the following list

l = [ 7, 3, 6, 9, 2, -1, -5, -4, -3]

to find the smallest value, a solution is to use the function min():

min(l)

which returns here:

-1

2 -- Find the smallest positive value

Now to find the smallest positive value a solution is to use a list comprehension and then min():

min([i for i in l if i > 0])

returns

2

3 -- Find the index of the smallest positive value

To find the index of the smallest positive value, a solution is to use index():

l.index(min([i for i in l if i > 0]))

returns here:

4

4 -- References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount