Maximum and Minimum K elements in Tuple using Python

PythonServer Side ProgrammingProgramming

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 −


 Live Demo

my_tuple = (7, 25, 36, 9, 6, 8)

print("The tuple is : ")

K = 2
print("The value of K has been initialized to ")
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 = tuple(my_result)

print("The result is : " )


The tuple is :
(7, 25, 36, 9, 6, 8)
The value of K has been initialized to
The result is :
(6, 7, 25, 36)


  • 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.

Published on 17-Apr-2021 12:52:04