Problem Formulation and Solution Overview
To make it more interesting, we have the following running scenario:
Method 1: Use Slicing
This example uses slicing in combination with the addition operator + to update an existing tuple element and insert an additional element.
nums_5day = (11, 12, 13, 14, 15) nums_6day = nums_5day[:2] + (18, 21) + nums_5day[3:] print(nums_6day)
The above code declares a Tuple containing projected temperatures for the next five (5) days. The results save to nums_5day.
The following line updates this Tuple by replacing an element and inserting an additional element using slicing. Thus making it projected temperatures for the next six (6) days. The results save to nums_6day and are output to the terminal.
| (11, 12, 18, 21, 14, 15) | 
Method 2: Use Unpack and Slicing
This example uses the unpack operator (*) and slicing to replace one (1) value from an existing tuple.
nums_5day = (11, 12, 13, 14, 15) new_5day = (30, *nums_5day[1:]) print(new_5day)
The above code declares a Tuple containing projected temperatures for the next five (5) days. The results save to nums_5day.
The following line replaces the current temperature of 11 to 30. Then, the unpack (*) operator and slicing are used to keep the remaining elements. The results save to new_5day and are output to the terminal.
| (30, 12, 13, 14, 15) | 
Method 3: Use List and List Comprehension
This example uses list and list comprehension to replace one (1) tuple value.
nums_5day = list((11, 12, 13, 14, 15)) new_5day = tuple([x + 5 if x == 13 else x for x in nums_5day]) print(new_5day)
The above code declares a Tuple containing projected temperatures for the next five (5) days. This is converted to a list and saved to nums_5day.
The following line uses list comprehension to replace the list element with the value of 13 to 18 (x+5). The results are converted to a Tuple, saved to new_5day and output to the terminal.
| (11, 12, 18, 14, 15) | 
Method 4: Use map() and a lambda
This example uses the map() function and a lambda to replace three (3) tuple values.
nums_5day = list((11, 12, 13, 14, 15)) new_5day = tuple(map(lambda x: x+3 if x >= 12 and x <= 14 else x, nums_5day)) print(new_5day)
The above code declares a Tuple containing projected temperatures for the next five (5) days. This is converted to a list and saved to nums_5day.
The following line calls the map() function and passes it one (1) argument, a lambda. This result returns a map object. If this object was output to the terminal, an object reference similar to below would display.
| <map object at 0x0000021A7F45B190> | 
This object is then converted from the map object to a Tuple and output to the terminal.
| (11, 15, 16, 17, 15) | 
Summary
This article has provided four (4) ways to change Tuple values to select the best fit for your coding requirements.
Good Luck & Happy Coding!
Programming Humor – Python

