any()
The built-in any()
function checks if any element in an iterable is true. It returns a Boolean value, True
if at least one element is truthy, otherwise False
:
>>> any([False, False, True])
True
>>> any([False, False, False])
False
any()
Signature
any(iterable)
Arguments
Argument | Description |
---|---|
iterable |
An iterable object whose elements are evaluated for truthiness. |
Return Value
- Returns
True
if at least one element in the iterable is truthy. - Returns
False
if the iterable is empty or all elements are falsy.
any()
Examples
With a list of Boolean values:
>>> any([False, False, True])
True
With a list of integers:
>>> any([0, 0, 1, 0])
True
With a list containing on truthy element:
>>> any(["", 42, {}, 0])
True
With an empty list:
>>> any([])
False
any()
Common Use Cases
The most common use cases for the any()
function include:
- Checking if any element in a list satisfies a condition
- Validating input where at least one field must be filled or true
- Evaluating multiple conditions compactly
any()
Real-World Example
Suppose you a function to decide whether to send a notification to a user based on multiple criteria like unread messages, pending tasks, or upcoming events:
>>> def should_notify(unread_messages, pending_tasks, upcoming_events):
... return any([unread_messages > 0, pending_tasks > 0, upcoming_events > 0])
...
>>> should_notify(0, 0, 1)
True
In this example, you use any()
to determine if any notification criteria are met, allowing you to notify the user accordingly.
Related Resources
Tutorial
How to Use any() in Python
If you've ever wondered how to simplify complex conditionals by determining if at least one in a series of conditions is true, then look no further. This tutorial will teach you all about how to use any() in Python to do just that.
For additional information on related topics, take a look at the following resources:
- Common Python Data Structures (Guide) (Tutorial)
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- How to Use Generators and yield in Python (Tutorial)
- Python any(): Powered Up Boolean Function (Course)
- Dictionaries and Arrays: Selecting the Ideal Data Structure (Course)
- Stacks and Queues: Selecting the Ideal Data Structure (Course)
- Records and Sets: Selecting the Ideal Data Structure (Course)
- Python Booleans: Leveraging the Values of Truth (Course)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)