Python | Check if any element in list satisfies a condition

Sometimes, while working with Python lists, we can have a problem to filter a list. One of the criteria of performing this filter operation can be checking if any element exists in list that satisfies a condition. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension
This problem can be easily solved using loops. But this method provides a one liner to solve this problem. List comprehension just checks for any element that satisfies a condition.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if any element in list satisfies a condition
# Using list comprehension
  
# initializing list
test_list = [4, 5, 8, 9, 10, 17]
  
# printing list
print("The original list : " + str(test_list))
  
# Check if any element in list satisfies a condition
# Using list comprehension
res = True in (ele > 10 for ele in test_list)
  
# Printing result
print("Does any element satisfy specified condition ? : " + str(res))

chevron_right


Output :



 
The original list : [4, 5, 8, 9, 10, 17]
Does any element satisfy specified condition ? : True

 

Method #2 : Using any()
This the most generic method to solve this particular problem. In this we just use the inbuilt function extended by Python library to solve this task. It checks for any element satisfying a condition and returns a True in case it finds any one element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if any element in list satisfies a condition
# Using any()
  
# initializing list
test_list = [4, 5, 8, 9, 10, 17]
  
# printing list
print("The original list : " + str(test_list))
  
# Check if any element in list satisfies a condition
# Using any()
res = any(ele > 10 for ele in test_list)
  
# Printing result
print("Does any element satisfy specified condition ? : " + str(res))

chevron_right


Output :

 
The original list : [4, 5, 8, 9, 10, 17]
Does any element satisfy specified condition ? : True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.