Python Exercise: Replace last value of tuples in a list
21. Replace the Last Value of Tuples in a List
Write a Python program to replace the last value of tuples in a list.
Sample Solution:
Python Code:
# Create a list of tuples, where each tuple contains three numbers.
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# Use a list comprehension to iterate through each tuple 't' in the list 'l'.
# For each tuple, create a new tuple by removing the last element and adding the number 100.
# The result is a list of modified tuples.
print([t[:-1] + (100,) for t in l])
Sample Output:
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to iterate over a list of tuples and replace the last element of each tuple with a fixed value.
- Write a Python program to use tuple slicing and concatenation to update the last value of every tuple in a list.
- Write a Python program to implement a function that modifies each tuple in a list by setting its last element to a new value.
- Write a Python program to create a new list of tuples where each tuple’s last element is replaced, using list comprehension.
Python Code Editor:
Previous: Write a Python program to print a tuple with string formatting.
Next: Write a Python program to remove an empty tuple(s) from a list of tuples.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics