This function returns True if at least one of the iterable's values is True. It is equivalent to
def any(iterable):
for element in iterable:
if element:
return True
return False
- when you need to search for a True value, and you don't know the number of values ahead of time
Imagine I own a business and I want to know which customers owe me money.
- iterate over all customers
- iterate over invoices for each customer
- check each invoice for a balance due
Assume I have these classes and methods
class Customer:
def invoices(self):
''' get all a customer's invoices '''
class Invoice:
def balance_due(self):
''' get the unpaid balance '''
I can code
customers_owing_money = [
customer
for customer in customers
if any(
invoice.balance_due() > 0
for invoice in customer.invoices()
)
]
I now have a list of customers with unpaid balances.
However, couldn't I write this instead?
customers_owing_money = [
customer
for customer in customers
for invoice in customer.invoices()
if invoice.balance_due() > 0
]
No, because this might produce duplicate customers in the final output. The any function avoids this problem by summarizing all the unpaid balances into a single True/False result.
See Stack Overflow: How exactly does the python any() function work?