| How to Use any() in Python |
|
writing a program for an employer's recruiting department schedule interviews with candidates who meet any of the following criteria
# recruit_developer.py
def schedule_interview(applicant):
print(f"Scheduled interview with {applicant['name']}")
applicants = [
{
"name": "Devon Smith",
"programming_languages": ["c++", "ada"],
"years_of_experience": 1,
"has_degree": False,
"email_address": "[email protected]",
},
{
"name": "Susan Jones",
"programming_languages": ["python", "javascript"],
"years_of_experience": 2,
"has_degree": False,
"email_address": "[email protected]",
},
{
"name": "Sam Hughes",
"programming_languages": ["java"],
"years_of_experience": 4,
"has_degree": True,
"email_address": "[email protected]",
},
]
for applicant in applicants:
knows_python = "python" in applicant["programming_languages"]
experienced_dev = applicant["years_of_experience"] >= 5
meets_criteria = (
knows_python
or experienced_dev
or applicant["has_degree"]
)
if meets_criteria:
schedule_interview(applicant)
using any()
for applicant in applicants:
knows_python = "python" in applicant["programming_languages"]
experienced_dev = applicant["years_of_experience"] >= 5
credentials = (
knows_python,
experienced_dev,
applicant["has_degree"],
)
if any(credentials):
schedule_interview(applicant)
any() can take any iterable as an argument
>>> any([0, 0, 1, 0]) True >>> any(set((True, False, True))) True >>> any(map(str.isdigit, "hello world")) False |
| How to Distinguish Between or and any() |
|
two main differences
Syntax
or is an operator which takes two arguments
>>> True or False Trueany() is a function which takes an iterable as an argument >>> any((False, True)) Truecan pass an iterable directly to any() to get similar behavior from or need to use a loop or a function like reduce() >>> import functools >>> functools.reduce(lambda x, y: x or y, (True, False, False)) Truelazy evaluation avoids testing a condition if any preceding condition is True below using or eliminates the need to call is_local() def knows_python(applicant):
print(f"Determining if {applicant['name']} knows Python...")
return "python" in applicant["programming_languages"]
def is_local(applicant):
print(f"Determine if {applicant['name']} lives near the office...")
should_interview = knows_python(applicant) or is_local(applicant)
using any() the same code will call sometimes unnecessary is_local() every time even when
knows_python() returns True
a lazy evaluation can be done with any() using a generator expression
any((meets_criteria(applicant) for applicant in applicants)) Return Value
any() returns a boolean indicating the truthy value of the iterableor returns the first truthy value it finds if or fails to find a truthy value it returns the last value in the iterable any() returns the actual value of the iterable or returns if a truthy value is in the iterable |