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
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
Using all() function we can check if all values are greater than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
The greater than ( > ) operator returns True when its left value is bigger than its right value. When the left value is smaller, or when they're equal, then > returns False .
Use the all()
function with a generator expression:
>>> my_list1 = [30, 34, 56] >>> my_list2 = [29, 500, 43] >>> all(i >= 30 for i in my_list1) True >>> all(i >= 30 for i in my_list2) False
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:
def all_30_or_up(ls): for i in ls: if i < 30: return False return True
e.g. as soon as you find a value that proves that there is a value below 30, you return False
, and return True
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.
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