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 - Assign a specific value to Non Max-Min elements in Tuple
When working with tuples, you may need to replace all elements except the maximum and minimum values with a specific value. Python provides the max() and min() methods to find extreme values, which can be used with conditional logic to transform tuple elements.
The max() method returns the largest element in an iterable, while min() returns the smallest. The tuple() method converts any iterable into a tuple.
Example
Here's how to replace non max-min elements with a specific value ?
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)
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)
Using List Comprehension
A more concise approach using list comprehension ?
my_tuple = (15, 30, 45, 60, 5, 75)
K = 100
max_val = max(my_tuple)
min_val = min(my_tuple)
result = tuple(elem if elem in [max_val, min_val] else K for elem in my_tuple)
print("Original tuple:", my_tuple)
print("Modified tuple:", result)
print(f"Max value {max_val} and min value {min_val} preserved")
Original tuple: (15, 30, 45, 60, 5, 75) Modified tuple: (100, 100, 100, 100, 5, 75) Max value 75 and min value 5 preserved
How It Works
-
Find extremes:
max()andmin()identify the largest and smallest values - Conditional check: Each element is compared against the max/min values
- Replace or preserve: Non-extreme elements are replaced with K, while max/min values remain unchanged
- Convert back: The result list is converted back to a tuple
Conclusion
This technique preserves only the maximum and minimum values in a tuple while replacing all other elements with a specified value. Use list comprehension for a more Pythonic approach, or a traditional loop for better readability.
