ProgrammingBackend Developer

Explain how the built-in function any() works in Python, what it is used for, and how it differs from all().

Pass interviews with Hintsage AI assistant

Answer

The any() function was introduced in Python 2.5 for convenient checking: whether there is at least one true element in an iterable object (for example, a list, tuple, generator). It is useful when you need to check whether at least one condition from many is met.

Historically, without it, you had to write a loop with a break upon finding an element or combine map and reduce — it was cumbersome and slow. The main problem that any() solves is the conciseness and readability of such checks.

The solution — any() and all() work with lazy evaluation (they stop as soon as they find False or True respectively). It is important to understand the difference: any() returns True upon the first true element, while all() returns True if all elements are true.

Example code:

nums = [0, 0, 3, 0] if any(nums): print('There is a non-zero element in the list')

Key features:

  • any() returns True if at least one element is true, otherwise False
  • all() returns True only if all elements are true
  • They work with lazy evaluation (they work correctly with infinite generators)

Trick questions.

What happens if you pass an empty list as an argument to any()?

any() will return False. This makes sense: there are no true elements in an empty sequence.

How is any() fundamentally different from all()?

any() checks for the presence of at least one true value. all() checks the truth of all values. Their results are opposite only for strictly empty collections.

Can you use any() with a generator that might be infinite?

Yes, you can, and thanks to lazy evaluation, any will stop as soon as it encounters True. If the generator never yields True, the function will not finish on its own.

def infinite_gen(): while True: yield 0 # any(infinite_gen()) — will run infinitely if there are no exit conditions

Typical mistakes and anti-patterns

  • Confusion between any and all
  • Passing a non-iterable object (will raise TypeError)
  • Attempting to control events in an infinite generator without exit conditions

Real-life example

Negative case

Want to check that at least one value is not None:

values = [None, None, None] if any(values): do_something() # Will never execute if we just forgot that None == False

Pros:

  • Using any() makes the code shorter

Cons:

  • If the set never contains true values, the code block will never execute

Positive case

Correct application — to look for at least one user over 30:

users = [{'age': 25}, {'age': 35}] if any(u['age'] > 30 for u in users): print('There is a user over 30')

Pros:

  • Concise, readable, works with any iterable object

Cons:

  • Implicitly stops at the first True, which sometimes requires explicit commenting of the logic