O.rka - 10 months ago 34

Python Question

`my_list1 = [30,34,56]`

my_list2 = [29,500,43]

How to I check if all values in list are >= 30?

`my_list1`

`my_list2`

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`

`>>> 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

Answer

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.