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
You could do the following:
This will return the values that are greater than 30 as True, and the values that are smaller as false.
The overall winner between using the np.sum, np.min, and all seems to be np.min in terms of speed for large arrays:
(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:
But when "all" needs to go through all the points, it is definitely much worse, and the np.min wins:
But using
can be very useful is one wants to know how many values are below x.
You can use
all()
:Note that this includes all numbers equal to 30 or higher, not strictly above 30.
Use the
all()
function with a generator expression:Note that this tests for greater than or equal to 30, otherwise
my_list1
would not pass the test either.If you wanted to do this in a function, you'd use:
e.g. as soon as you find a value that proves that there is a value below 30, you return
False
, and returnTrue
if you found no evidence to the contrary.Similarly, you can use the
any()
function to test if at least 1 value matches the condition.I write this function
Then
Empty list on min() will raise ValueError. So I added
if not x
in condition.There is a builtin function
all
:Being limit the value greater than which all numbers must be.