Yandex

Python any() Function – Check if Any Element is True



Python any() Function

The any() function in Python is used to check if at least one element in an iterable (like a list, tuple, or set) is True. If it finds even one True value, it immediately returns True.

Syntax

any(iterable)

Parameters:

  • iterable – A list, tuple, set, string, dictionary, or any iterable containing values.

Returns:

  • True – if at least one element is true (non-zero or non-empty)
  • False – if all elements are false (zero, empty, or None)

Example 1: List with One True Value

values = [0, False, 5, None]
print(any(values))
True

Example 2: All False Values

values = [0, "", False, None]
print(any(values))
False

Example 3: Using any() with Strings

words = ["", "", "hello"]
print(any(words))
True

Because "hello" is non-empty, it's considered True.

Use Case: Check if Any Input Field is Filled

name = ""
email = "example@example.com"
phone = ""

if any([name, email, phone]):
    print("At least one field is filled.")
else:
    print("All fields are empty.")
At least one field is filled.

How any() Works Internally

  • It checks each item from left to right.
  • Stops as soon as it finds the first True value (short-circuiting).
  • Returns False if no True values are found.

Common Mistakes

  • Passing non-iterable like any(5) → ❌ Raises TypeError
  • Expecting it to check if values are equal or valid — it only checks truthiness

Interview Tip

any() is often used to simplify conditional checks across multiple values. It helps avoid writing long or chains like if a or b or c.

Summary

  • any() returns True if at least one value is truthy.
  • Works on lists, tuples, sets, dictionaries, strings, etc.
  • Stops early when it finds the first True.

Practice Problem

Write a program that checks if any number in a list is greater than 10:

numbers = [2, 5, 8, 12, 4]
result = any(n > 10 for n in numbers)
print("Any number > 10?", result)
Any number > 10? True


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M