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 – Maximum of K element in other list
Sometimes we need to find the maximum element from one list where the corresponding elements in another list match a specific value K. This can be achieved using iteration, the append() method, and the max() function.
Example
Below is a demonstration of finding the maximum element from the first list where corresponding elements in the second list equal K ?
my_list_1 = [62, 25, 32, 98, 75, 12, 46, 53]
my_list_2 = [91, 42, 48, 76, 23, 17, 42, 83]
print("The first list is:")
print(my_list_1)
print("The first list after sorting is:")
my_list_1.sort()
print(my_list_1)
print("The second list is:")
print(my_list_2)
print("The second list after sorting is:")
my_list_2.sort()
print(my_list_2)
K = 42
print("The value of K is")
print(K)
my_result = []
for index in range(len(my_list_1)):
if my_list_2[index] == K:
my_result.append(my_list_1[index])
my_result = max(my_result)
print("The result is:")
print(my_result)
The first list is: [62, 25, 32, 98, 75, 12, 46, 53] The first list after sorting is: [12, 25, 32, 46, 53, 62, 75, 98] The second list is: [91, 42, 48, 76, 23, 17, 42, 83] The second list after sorting is: [17, 23, 42, 42, 48, 76, 83, 91] The value of K is 42 The result is: 46
How It Works
The algorithm works by iterating through both lists simultaneously and collecting elements from the first list where the corresponding element in the second list equals K. After sorting both lists, we can see that K=42 appears at indices where the first list contains values 32 and 46. The maximum of these values is 46.
Alternative Approach Using List Comprehension
Here's a more concise way to achieve the same result ?
list_1 = [62, 25, 32, 98, 75, 12, 46, 53]
list_2 = [91, 42, 48, 76, 23, 17, 42, 83]
list_1.sort()
list_2.sort()
K = 42
# Find maximum using list comprehension
result = max([list_1[i] for i in range(len(list_1)) if list_2[i] == K])
print(f"Maximum element from first list where second list equals {K}: {result}")
Maximum element from first list where second list equals 42: 46
Conclusion
This technique allows you to find the maximum element from one list based on matching conditions in another list. The list comprehension approach provides a more concise solution while maintaining the same functionality.
