Python - Assign a specific value to Non Max-Min elements in Tuple

PythonServer Side ProgrammingProgramming

When it is required to assign a specific value to the non max-min elements in a tuple, the ‘max’ method, the ‘min’ method, the ‘tuple’ method and a loop can be used.

The ‘max’ method returns the maximum value among all of the elements in an iterable. The ‘min’ method returns the minimum value among all of the elements in an iterable.

The ‘tuple’ method converts a given value/iterable into a tuple type.

Below is a demonstration for the same −

Example

 Live Demo

my_tuple = (25, 56, 78, 91, 23, 11, 0, 99, 32, 10)
print("The tuple is : ")
print(my_tuple)
K = 5
print("K has been assigned to " + str(K))
my_result = []
for elem in my_tuple:
   if elem not in [max(my_tuple), min(my_tuple)]:
      my_result.append(K)
   else:
      my_result.append(elem)
      my_result = tuple(my_result)
print("The tuple after conversion is : " )
print(my_result)

Output

The tuple is :
(25, 56, 78, 91, 23, 11, 0, 99, 32, 10)
K has been assigned to 5
The tuple after conversion is :
(5, 5, 5, 5, 5, 5, 0, 99, 5, 5)

Explanation

  • A tuple is defined, and is displayed on the console.
  • The value of ‘K’ is defined and displayed.
  • An empty list is created.
  • The tuple is iterated over, and the maximum and minimum values are determined.
  • If these values are not in the tuple, it is appended to the empty list.
  • This list is converted to a tuple.
  • It is then displayed as output on the console.
raja
Published on 11-Mar-2021 17:08:45
Advertisements