Python any(): Powered Up Boolean Function (Overview)

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 course, you’ll learn how to:

  • Use any() and not any()
  • Elimate long or chains
  • Use any() with list comprehensions
  • Evalute values that aren’t explicitly True or False
  • Distinguish between any() and or
  • Use short-circuiting

Sample Code (.zip)

2.0 KB

Course Slides (.pdf)

451.2 KB

00:00 Hello, and welcome to this course on Python any(), the powered up Boolean function.

00:07 Free yourself from chains of or. So if you’ve ever written code that might have various conditions and you find yourself chaining together with or—so in this case, you can see that we have if x is True or y is True or z is True or foo is True, then you do things. Now, there must be an easier way to write this, right? Well, there you go. any() is for you.

00:34 Another way that any() can be extremely handy is with eliminating unneeded for loops. So say you had this list of students that represented whether they passed the test or not. You have three False and one True.

00:48 How you might approach this is you’d have a sentinel value or a flag value called any_pass, and you set that to False at the beginning.

00:57 Then you create a for loop that goes through each student and checks if a particular student is True. If it is True, then you can set that sentinel value to True, which indicates that there has been one student that has passed, and then you can break out of the for loop because you don’t need to check any more.

01:17 And then you can finally check at the end of your for loop that if any_pass is True, then you can do things because at least one student has passed. However, with the any() function, you can write all this code like this. More on that later.

01:35 You’re going to cover a bunch of stuff in this course about any(), from its basic usage to how to eliminate or deal with long or chains.

01:43 You’re going to learn about how to use any() with list comprehensions, which is a very powerful feature. You’ll learn about the inverse, not any(). You’ll learn about how any() evaluates values that aren’t explicitly True or False.

01:57 You’ll learn some important differences between any() and or, and when you might want to use one or the other. And you will also learn what short-circuiting is.

02:08 So without further ado, coming up next is the basic usage of the any() function.

Become a Member to join the conversation.