Program to check if all the values in a list that are greater than a given value in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we will check whether all the elements in a list are greater than a number or not. For example, we have a list [1, 2, 3, 4, 5] and a number 0. If every value in the list is greater than the given value then, we return True else False.

It's a simple program. We write it in less than 3 minutes. Try it yourself first. If you are not able to find the solution, then, follow the below steps to write the program.

  • Initialise a list and any number
  • Loop through the list.
If yes, return **False**
  • Return True.

Example

## initializing the list
   values = [1, 2, 3, 4, 5]
## number num = 0
   num_one = 1
## function to check whether all the values of the list are greater than num or not
   def check(values, num):
   ## loop
      for value in values:
         ## if value less than num returns False
         if value <= num:
            return False
   ## if the following statement executes i.e., list contains values which are greater than given num
   return True
   print(check(values, num))
   print(check(values, num_one))

If you run the above program,

Output

True False

Another way to find it is using the all() inbuilt method. all() method returns True if every element from the iterable is True else it returns False. Let's see the program using all() method.

## initializing the list
values = [1, 2, 3, 4, 5]
## number
num = 0
num_one = 1
## function to check whether all the values of the list are greater than num or not def check(values, num):
   ## all() method
   if all(value > num for value in values):
      return True
   else:
      return False
print(check(values, num))
print(check(values, num_one))

If you run the above program,

Output

True 
False

If you have any doubts regarding the program, please do mention them in the comment section.

raja
Published on 27-Aug-2019 12:12:11
Advertisements