Thought leadership from the most innovative tech companies, all in one place.

How to Check Whether at Least One Value is True in Python

image

In the previous article, we saw how to check whether all the values in an iterable object are True in Python.

In this article, we are going to see whether there is at least one condition that is satisfied in an iterable object in Python.

Let us suppose that we have the following list:

july_earnings = 2000
august_earnings = 1000
september_earnings = 3000

third_quarter_earnings = [july_earnings > 4000, august_earnings > 4000, september_earnings > 4000]

We want to see whether we have earned more than 4000 in at least 1 month.

One way to check it would be to loop through all the elements and check whether any of the values is True. If it is True, then we can return True immediately and stop iterating any further.

If we have gone all the way until the end of the list and haven’t reached any True condition, we just return False.

Let us see this in the implementation:

def are_conditions_met(conditions):
	for condition in conditions:
		if condition:
			return True
	return False

Another faster way that can help us without having to do an iteration through every element is using the function any():

def are_conditions_met(conditions):
	return any(conditions)

Yes, I know, it is so trivial.

Let us see a full example related to this:

july_earnings = 2000
august_earnings = 1000
september_earnings = 3000
third_quarter_earnings = [july_earnings > 4000, august_earnings > 4000, september_earnings > 4000]

def are_conditions_met(conditions):
	if any(conditions):
		print("You have earned more than 4000 in at least 1 month.")
	else:
		print("It seems that you have to improve your product or your sales campaign.")
	return True

print(are_conditions_met(third_quarter_earnings)) # False

It’s that simple, yes.

There is no need to do any iteration, or any complicated check.

It does come with the limitation that you are not sure which condition is met, or which element in the iterable object is True, but you may not always need to know that anyway.

I hope you find this useful.




Continue Learning