- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum and Minimum K elements in Tuple using Python
When it is required to find the maximum and minimum K elements in a tuple, the ‘sorted’ method is used to sort the elements, and enumerate over them, and get the first and last elements.
Below is the demonstration of the same −
Example
my_tuple = (7, 25, 36, 9, 6, 8) print("The tuple is : ") print(my_tuple) K = 2 print("The value of K has been initialized to ") print(K) my_result = [] my_tuple = list(my_tuple) temp = sorted(my_tuple) for idx, val in enumerate(temp): if idx < K or idx >= len(temp) - K: my_result.append(val) my_result = tuple(my_result) print("The result is : " ) print(my_result)
Output
The tuple is : (7, 25, 36, 9, 6, 8) The value of K has been initialized to 2 The result is : (6, 7, 25, 36)
Explanation
A tuple is defined, and is displayed on the console.
The value of K is defined.
An empty list is defined.
The tuple is converted to a list.
It is sorted and stored in a variable.
This is iterated over, and if it is less than K or greater than difference between length of list and K, it is appended to the empty list.
This is the output that is displayed on the console.
Advertisements
To Continue Learning Please Login
Login with Google