Check if any value in Python List is greater than a value

In this article, we will learn how to check if any element in list is greater than a given value in Python.

Table Of Contents

Solution 1 : Using any() function

To verify if any element in a list is greater than a given value, apply this 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 is greater than the given value. So, if any elements in this boolean list is True, then it means there is atleast an element in original list, which is greater than given value. 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 number in list is greater than 30.

# A list of numbers
listOfNumbers = [17, 18, 25, 34, 10, 28, 29, 26]

minValue = 30

# Check if any value in a Python List is greater than 30
if any(num > minValue  for num in listOfNumbers):
    print('Yes, atleast an element in List is greater than 30')
else:
    print('No, all elements in List are smaller than or equal to 30')

Output:

Yes, atleast an element in List is greater than 30

Here, we confirmed that atleast a number in list is greater than 30.

Solution 2 : Using for-loop

Iterate over all elements of a list using a for loop and check if any element is greater than given value or not. During iteration, if you find any element that is greater than 30, then break the loop, because search is successful.

Let’s see an example, where we will check if any number in list is greater than 30.

# A list of numbers
listOfNumbers = [17, 18, 25, 34, 10, 28, 29, 26]

minValue = 30
result = False

# Iterate over all numbers in a list and check 
# if any values in a Python List is greater than 30
for num in listOfNumbers:
    if num > minValue:
        result = True
        break

if result:
    print('Yes, atleast an element in List is greater than 30')
else:
    print('No, all elements in List are smaller than or equal to 30')

Output:

Yes, atleast an element in List is greater than 30

Here, we confirmed that atleast a number in list is greater than 30.

Summary

Today, we learned how to check if any element in a list is greater than a given value in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top