As a Python programmer, you’ll frequently deal with Booleans and conditional statements—sometimes very complex ones. In those situations, you may need to rely on tools that can simplify logic and consolidate information. Fortunately, any() in Python is such a tool. It looks through the elements in an iterable and returns a single value indicating whether any element is true in a Boolean context, or truthy.

In this tutorial, you’ll learn:

  • How to use any()
  • How to decide between any() and or

Let’s dive right in!

How to Use any() in Python

Imagine that you’re writing a program for your employer’s recruiting department. You might want to schedule interviews with candidates who meet any of the following criteria:

  1. Know Python already
  2. Have five or more years of developer experience
  3. Have a degree

One tool you could use to write this conditional expression is or:

Language: Python
# 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": "devon@email.com", }, { "name": "Susan Jones", "programming_languages": ["python", "javascript"], "years_of_experience": 2, "has_degree": False, "email_address": "susan@email.com", }, { "name": "Sam Hughes", "programming_languages": ["java"], "years_of_experience": 4, "has_degree": True, "email_address": "sam@email.com", }, ] 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) 

In the above example, you check each applicant’s credentials and schedule an interview if the applicant meets any of your three criteria.

If you execute this code, then you’ll see that Susan and Sam will get interviews:

Language: Shell
$ python recruit_developer.py Scheduled interview with Susan Jones Scheduled interview with Sam Hughes 

Read the full article at https://realpython.com/any-python/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]