# Check if any elements in list match a condition in Python

In this article, we will learn how to check if any element in list matches a given condition in Python.

## Solution 1 : Using all() function

To verify if any element in list matches a condition, apply the given condition to each element of list and store results in a boolean list. Size of this boolean list will be equal to the size of the original list. Also, a True value in this boolean list tells that the corresponding value in original list matches the condition. So, if any element in this boolean list is True, then it means, there is at least an element in original list that matches the given condition. Now to check if any element in list is True, we can use the any() function. It accepts a sequence of boolean type elements and returns True if any element in that sequence evaluates to True.

Let’s see an example, where we will check if any numbers in a list is odd or not.

# Check if a Number is Odd
def IsOdd(num):
result = False
if num % 2 == 1:
result = True
return result

listOfNumbers = [22, 78, 54, 32, 93, 80, 74]

# Check if any element of a list matches a condition
# i.e. any element is Odd
if any(IsOdd(num)  for num in listOfNumbers):
print('Yes, at least an element in List is Odd')
else:
print('Not a single element in List is Odd')

Output

Yes, at least an element in List is Odd

Here, we confirmed that atleast an element in the list is True.

## Solution 2 : Using for-loop

Iterate over all elements of a list using a for loop and apply the given condition on each element. For any element, if the given condition evaluates to True, then it means that there is atleast an element in the list that matches the given condition. If all evaluates to False, then it means no element in the list matches the given condition.

Let’s see an example, where we will check if any number in the list is odd or not.

# Check if a Number is Odd
def IsOdd(num):
result = False
if num % 2 == 1:
result = True
return result

listOfNumbers = [68, 80, 54, 42, 91, 98, 74]

result = False

# Check if any element of a list matches a condition
# i.e. any element is Odd
for num in listOfNumbers:
if IsOdd(num):
result = True
break

if result:
print('Yes, at least an element in List is Odd')
else:
print('Not a single element in List is Odd')

Output

Yes, at least an element in List is Odd

Here, we confirmed that atleast an element in the list is True.

## Summary

We learned different ways to check if any element in list satisfies a given condition or not. Thanks.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top