Python | Test if any list element returns true for condition

Sometimes, while coding in Python, we can have a problem in which we need to filter a list on basis of condition met by any of the element. This can have it’s application in web development domain. Let’s discuss a shorthand in which this task can be performed.

Method : Using any() + list comprehension
The simplest way and shorthand to solve this problem is to combine the functionalities of inbuilt any() and list comprehension for rendering condition logic and list iteration. The any() returns true if any of the list element matches the condition.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Test if any list element returns true for condition
# Using any() + list comprehension
  
# initializing list
test_list = [6, 4, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Test if any list element returns true for condition
# Using any() + list comprehension
res = any(x % 5 for x in test_list)
  
# Printing result
print("Does list contain any element divisible by 5? : " + str(res))

chevron_right


Output :

 
The original list : [6, 4, 8, 9, 10]
Does list contain any element divisible by 5? : 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.