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

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

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`

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`

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`

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.

Ads

License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Ads

Ads