
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
Assign Specific Value to Non-Max/Min Elements in Tuple in Python
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
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.
Advertisements