Finding Nemo or check a Python list if there is one or all elements matching a condition
Yeah we all can loop, but can you any or all?
Checking if condition matches for at least one element of an iterable (e.g. list, tuple, set)
# check if any number is dividable by 7
dividable_by_7 = False
for i in [0, 2, 3, 9, 14, 19]:
if i % 7 == 0:
dividable_by_7 = True
break
print(f"dividable by 7 is {dividable_by_7}")
In Python you can write that nicer with the builtin method any():
li = [0, 2, 3, 9, 14, 19]
dividable_by_7 = any(i % 7 == 0 for i in li)
print(f'dividable by 7 is {dividable_by_7}')
But who doesn’t like a one-liner (that is understandable):
print(f'dividable by 7 is {any(i % 7 == 0 for i in [0, 2, 3, 9, 14, 19])}')
Very similar is the case if you want to check if all elements of a list satisfy the condition.
First we start off we the good old for loop which is interrupted when an element does not meet the requirements.
# check if every number is smaller than 15
all_smaller = True
for i in [2, 3, 9, 19]:
if i >= 15:
all_smaller = False
break
print(f"all smaller than 15 is {all_smaller}")
Next we use the all() method step by step
li = [2, 3, 9, 19]
all_smaller = all(i < 15 for i in li)
print(f"all smaller than 15 is {all_smaller}")
The one-liner is pretty much mandatory 😛
print(f"all smaller than 15 is {all(i < 15 for i in [2, 3, 9, 19])}")
Enjoy!