Check if any element in a list satisfies a condition in Python
Welcome everyone, in this post, we will see how to check if any element in a list satisfies a condition in Python. There can be many instances when we need to find out if whether some elements in a Python list satisfy a given condition or not. We will learn to do that in this tutorial.
In order to check if any element in a Python list satisfies a given condition or not we will be using list comprehension and any() method. Let’s see these two methods one by one.
List Comprehension method
This method uses list comprehension as shown below. We can also use a loop for this program but list comprehension is the shorter way of doing the same. Have a look at this code.
given_list = ['I', 'am', 'somebody'] ret = True in (len(i)>2 for i in given_list) print("There exists a string in the list with length more than 2: ", ret)
Output:
There exists a string in the list with length more than 2: True
In the above code, we have first initialized a list of strings. The condition specified is that the length of the string should be more than two. The program returns true as there exists a string ‘somebody’ with length 8.
Any() method
We can also use any() method for the given problem. This method will return true if any of the expressions inside the function returns True. See the below code to understand its working.
given_list = ['I', 'am', 'somebody'] ret = any(len(i)>2 for i in given_list) print("There exists a string in the list with length more than 2: ", ret)
Output:
There exists a string in the list with length more than 2: True
Thank you.
Also read: Python program to check a number is Narcissistic number or not
Leave a Reply