Python any()
The any() built-in function takes in an iterable object such as a list or tuple and returns True if any of the elements in the iterable are true. If none of the elements present in the iterable are true, any() will return False.
Syntax
any(iterable)
The iterable is any sequence or collection that can be traversed, such as a dictionary or list.
The inside of the pseudocode can be broken down in the following way:
def any(iterable):
for element in iterable:
if element:
return True
return False
Inside the loop, at the first instance of an element existing in the iterable, execution will stop and True will be returned. If the end of the loop is reached and the element is not found, False is returned instead.
Example
In the following example, the any() function is used to return a boolean after checking a list and a dictionary:
print(any([True, 0, False]))print(any({0 : "Off"}))
The following output will be printed to the shell:
TrueFalse
Codebyte Example
In the example below, a team of Pokemon are created in preparation for a battle. They are selected based on various properties such as "level" and "type(s)". The any() function is ultimately used to pick out the Pokemon that meet that criteria:
All contributors
- Anonymous contributor
- TekASip
BrandonDusch
Christine_Yang
christian.dinh- Anonymous contributor
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours