Open In App

Check if any element in list satisfies a condition-Python

Last Updated : 11 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the condition.

Using any()

any() is the most efficient way to check if any element in a list satisfies a condition. It short-circuits, meaning it stops checking as soon as it finds a match, making it ideal for performance-sensitive tasks.

Python
a = [4, 5, 8, 9, 10, 17]

res = any(ele > 10 for ele in a)
print(res)

Output
True

Explanation: any() iterates through the list and checks if any element is greater than 10. It stops as soon as it finds the first matching element.

Using next()

next() allows us to retrieve the first matching element from a generator. When used with a conditional generator expression, it can efficiently check for the presence of an element that satisfies a condition.

Python
a = [4, 5, 8, 9, 10, 17]

res = next((True for ele in a if ele > 10), False)
print(res)

Output
True

Explanation: next() iterates through the list and checks if any element is greater than 10. It stops as soon as it finds the first matching element and returns True otherwise, it returns False.

Using filter()

filter() applies a condition to each element and returns an iterator of matching values. However, converting this iterator to a list just to check if it has elements makes it inefficient for this use case.

Python
a = [4, 5, 8, 9, 10, 17]

res = bool(list(filter(lambda x: x > 10, a)))
print(res)

Output
True

Explanation: filter() extracts elements greater than 10, converts them into a list and bool() checks if the list is non-empty. It does not short-circuit.

Using loop

A traditional for loop can manually check each element and break as soon as a match is found. While effective, it is less readable than any().

Python
a = [4, 5, 8, 9, 10, 17]
res = False

for ele in a:
    if ele > 10:
        res = True
        break
print(res)

Output
True

Explanation: for loop iterates through the list and checks if any element is greater than 10. It sets res to True and breaks the loop as soon as it finds the first matching element.


Next Article
Practice Tags :

Similar Reads