[python] Check if all values in list are greater than a certain number

my_list1 = [30,34,56]
my_list2 = [29,500,43]

How to I check if all values in list are >= 30? my_list1 should work and my_list2 should not.

The only thing I could think of doing was:

boolean = 0
def func(ls):
    for k in ls:
        if k >= 30:
            boolean = boolean + 1
        else:
            boolean = 0
    if boolean > 0:
        print 'Continue'
    elif boolean = 0:
        pass

Update 2016:

In hindsight, after dealing with bigger datasets where speed actually matters and utilizing numpy...I would do this:

>>> my_list1 = [30,34,56]
>>> my_list2 = [29,500,43]

>>> import numpy as np
>>> A_1 = np.array(my_list1)
>>> A_2 = np.array(my_list2)

>>> A_1 >= 30
array([ True,  True,  True], dtype=bool)
>>> A_2 >= 30
array([False,  True,  True], dtype=bool)

>>> ((A_1 >= 30).sum() == A_1.size).astype(np.int)
1
>>> ((A_2 >= 30).sum() == A_2.size).astype(np.int)
0

You could also do something like:

len([*filter(lambda x: x >= 30, my_list1)]) > 0

This question is related to python list function max

The answer is


 a = [[a, 2], [b, 3], [c, 4], [d, 5], [a, 1], [b, 6], [e, 7], [h, 8]]

I need this from above one

 a = [[a, 3], [b, 9], [c, 4], [d, 5], [e, 7], [h, 8]]
a.append([0, 0])
for i in range(len(a)):
     for j in range(i + 1, len(a) - 1):
            if a[i][0] == a[j][0]:
                    a[i][1] += a[j][1]
                    del a[j]
a.pop()
        

You can use all():

my_list1 = [30,34,56]
my_list2 = [29,500,43]
if all(i >= 30 for i in my_list1):
    print 'yes'
if all(i >= 30 for i in my_list2):
    print 'no'

Note that this includes all numbers equal to 30 or higher, not strictly above 30.


The overall winner between using the np.sum, np.min, and all seems to be np.min in terms of speed for large arrays:

N = 1000000
def func_sum(x):
    my_list = np.random.randn(N)
    return np.sum(my_list < x )==0

def func_min(x):
    my_list = np.random.randn(N)
    return np.min(my_list) >= x

def func_all(x):
    my_list = np.random.randn(N)
    return all(i >= x for i in my_list)

(i need to put the np.array definition inside the function, otherwise the np.min function remembers the value and does not do the computation again when testing for speed with timeit)

The performance of "all" depends very much on when the first element that does not satisfy the criteria is found, the np.sum needs to do a bit of operations, the np.min is the lightest in terms of computations in the general case.

When the criteria is almost immediately met and the all loop exits fast, the all function is winning just slightly over np.min:

>>> %timeit func_sum(10)
10 loops, best of 3: 36.1 ms per loop

>>> %timeit func_min(10)
10 loops, best of 3: 35.1 ms per loop

>>> %timeit func_all(10)
10 loops, best of 3: 35 ms per loop

But when "all" needs to go through all the points, it is definitely much worse, and the np.min wins:

>>> %timeit func_sum(-10)
10 loops, best of 3: 36.2 ms per loop

>>> %timeit func_min(-10)
10 loops, best of 3: 35.2 ms per loop

>>> %timeit func_all(-10)
10 loops, best of 3: 230 ms per loop

But using

np.sum(my_list<x)

can be very useful is one wants to know how many values are below x.


...any reason why you can't use min()?

def above(my_list, minimum):
    if min(my_list) >= minimum:
        print "All values are equal or above", minimum
    else:
        print "Not all values are equal or above", minimum

I don't know if this is exactly what you want, but technically, this is what you asked for...


There is a builtin function all:

all (x > limit for x in my_list)

Being limit the value greater than which all numbers must be.


I write this function

def larger(x, than=0):
    if not x or min(x) > than:
        return True
    return False

Then

print larger([5, 6, 7], than=5)  # False
print larger([6, 7, 8], than=5)  # True
print larger([], than=5)  # True
print larger([6, 7, 8, None], than=5)  # False


Empty list on min() will raise ValueError. So I added if not x in condition.


You could do the following:

def Lists():

    my_list1 = [30,34,56]
    my_list2 = [29,500,43]

    for element in my_list1:
        print(element >= 30)

    for element in my_list2:
        print(element >= 30)

Lists()

This will return the values that are greater than 30 as True, and the values that are smaller as false.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to max

Min and max value of input in angular4 application numpy max vs amax vs maximum mongodb how to get max value from collections Python find min max and average of a list (array) Max length UITextField How to find the highest value of a column in a data frame in R? MAX function in where clause mysql Check if all values in list are greater than a certain number How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows