Python | Check if all the values in a list are less than a given value
Given a list, write a Python program to check if all the values in a list are less than the given value.
Examples:
Input : list = [11, 22, 33, 44, 55]
value = 22
Output : No
Input : list = [11, 22, 33, 44, 55]
value = 65
Output : Yes
Method #1: Traversing the list
Compare each element by iterating through the list and check if all the elements in the given list are less than the given value or not.
Python3
def CheckForLess(list1, val):
for x in list1:
if val < = x:
return False
return True
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if (CheckForLess(list1, val)):
print ( "Yes" )
else :
print ( "No" )
|
Time complexity: O(n) – the function traverses through the entire list once.
Auxiliary space: O(1) – the function only uses a few variables for comparison and does not create any new data structures.
Method #2: Using all() function Using all() function we can check if all values are less than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.
Python3
def CheckForLess(list1, val):
return ( all (x < val for x in list1))
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if (CheckForLess(list1, val)):
print ( "Yes" )
else :
print ( "No" )
|
Method #3 : Using max() method
Python3
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if ( max (list1)>val):
print ( "No" )
else :
print ( "Yes" )
|
Time Complexity: O(n), where n is length of list1.
Auxiliary Space: O(1)
Method #4: Using numpy
Here’s the numpy library approach to check if all values in a list are less than a given value:
Python3
import numpy as np
def CheckForLess(list1, val):
arr = np.array(list1)
if np. all (arr < val):
return 'Yes'
else :
return 'No'
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 22
print (CheckForLess(list1, val))
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
print (CheckForLess(list1, val))
|
Output:
No
Yes
Time Complexity: O(n), where n is the length of the input list, since we need to convert the list to a numpy array, and then use numpy’s ‘all’ function to check if all elements are less than the given value.
Space Complexity: O(n), where n is the length of the input list, since we create a numpy array of size n.
Last Updated :
22 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...