
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum of K Elements in Another List Using Python
When it is required to get the maximum of K elements based on another list, a simple iteration, the ‘append’ method and the ‘max’ methods are used.
Example
Below is a demonstration of the same −
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 first 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)
Output
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 first list after sorting is : [17, 23, 42, 42, 48, 76, 83, 91] The value of K is 42 The result is : 46
Explanation
Two lists are defined and are displayed on the console.
They are sorted using the ‘sort’ method and displayed on the console.
The value of K is defined and is displayed on the console.
An empty list is defined.
The first list is iterated over.
The element of a specific index in the second list is assigned to the value K.
This element in the index of first list is appended to the empty list.
The maximum of elements in this list is considered.
This element is assigned to a variable.
It is displayed as output on the console.
Advertisements