w3resource

Python Exercise: Replace last value of tuples in a list

Python tuple: Exercise-21 with Solution

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:

Flowchart: Replace last value of tuples in a list

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/tuple/python-tuple-exercise-21.php