Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Test if elements of list are in Min/Max range from other list
When it is required to test if all elements from one list fall within the minimum and maximum range of another list, we can iterate through the elements and check if each one lies between the min and max values.
Example
Below is a demonstration of the same −
my_list = [5, 6, 4, 7, 8, 13, 15]
print("The list is:")
print(my_list)
range_list = [4, 7, 10, 6]
print("The range list is:")
print(range_list)
# Find min and max values from the main list
min_val = min(my_list)
max_val = max(my_list)
print(f"Min value: {min_val}, Max value: {max_val}")
# Check if all elements in range_list are within min/max range
my_result = True
for elem in range_list:
if elem < min_val or elem > max_val:
my_result = False
break
if my_result:
print("All elements are in the min/max range")
else:
print("All elements are not in the min/max range")
Output
The list is: [5, 6, 4, 7, 8, 13, 15] The range list is: [4, 7, 10, 6] Min value: 4, Max value: 15 All elements are in the min/max range
Using List Comprehension
A more concise approach using list comprehension and the all() function −
my_list = [5, 6, 4, 7, 8, 13, 15]
range_list = [4, 7, 10, 6]
min_val = min(my_list)
max_val = max(my_list)
# Check using all() and list comprehension
result = all(min_val <= elem <= max_val for elem in range_list)
if result:
print("All elements are in the min/max range")
else:
print("All elements are not in the min/max range")
Output
All elements are in the min/max range
Example with Elements Outside Range
Here's an example where some elements fall outside the range −
my_list = [5, 6, 7, 8]
range_list = [4, 7, 10, 6] # 4 and 10 are outside range
min_val = min(my_list) # 5
max_val = max(my_list) # 8
result = all(min_val <= elem <= max_val for elem in range_list)
print(f"Range: [{min_val}, {max_val}]")
print(f"Test elements: {range_list}")
print(f"All in range: {result}")
Output
Range: [5, 8] Test elements: [4, 7, 10, 6] All in range: False
Explanation
The main list is defined to establish the range boundaries.
The
min()andmax()functions find the minimum and maximum values.Each element in the test list is checked to see if it falls within the range [min_val, max_val].
The
all()function returnsTrueonly if all elements satisfy the condition.The result indicates whether all elements are within the specified range.
Conclusion
Use all() with list comprehension for a concise solution. The approach checks if every element in the test list falls between the minimum and maximum values of the reference list.
