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.
# Python program to check if all values # in the list are less than given value # Function to check the value def CheckForLess(list1, val):
# traverse in the list
for x in list1:
# compare with all the
# values with value
if val < = x:
return False
return True
# Driver code list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if (CheckForLess(list1, val)):
print ( "Yes" )
else :
print ( "No" )
|
Yes
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.
# Python program to check if all values # in the list are less than given value # Function to check the value def CheckForLess(list1, val):
return ( all (x < val for x in list1))
# Driver code list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if (CheckForLess(list1, val)):
print ( "Yes" )
else :
print ( "No" )
|
Yes
Method #3 : Using max() method
# Python program to check if all values # in the list are less than given value list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
if ( max (list1)>val):
print ( "No" )
else :
print ( "Yes" )
|
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:
import numpy as np
# Function to check if all elements # in list1 are less than val def CheckForLess(list1, val):
# Convert list1 to a numpy array
arr = np.array(list1)
# Check if all elements are less
# than val using numpy's 'all' function
if np. all (arr < val):
return 'Yes'
else :
return 'No'
# Driver Code list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 22
print (CheckForLess(list1, val)) # Output: No
list1 = [ 11 , 22 , 33 , 44 , 55 ]
val = 65
print (CheckForLess(list1, val)) # Output: Yes
|
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.