I have a list with the these values.
lst1 = [1,-2,-4,-8,-9,-12,0,39,12,-3,-7]
I need to get the max value that is less that zero.
If I do print max(last)
- I get 39 and what is need is -2.
print max(p < 0 for p in lst1)
, I get True and not -2
To check that the list contains only one element, you could use a couple of try , except statements to check that (1) you can access the first element, and (2) you can't access a second element. Really, the most Pythonic way is to just use len .
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().
Use the all() function to check if all values in a list are greater than a certain number, e.g. if all(item > 2 for item in my_list): . The all() function will return True if all of the values in the list are greater than the specified number and False otherwise. Copied!
Never mind, I figured out and it should be
print max(p for p in lst1 if p < 0)
just filter the list first:
max(filter(lambda x:x<0,ls))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With