Replace Last Tuple Element

Tags: replace, tuple

Write a Python program to replace the last value of tuples in a list.

Example 1:

Input: [(10, 20, 40), (40, 50, 60)], 100 
Output: [(10, 20, 100), (40, 50, 100)]

Example 2:

Input: [(1, 2, 3), (4, 5, 6)], 9 
Output: [(1, 2, 9), (4, 5, 9)]

For each tuple in the list, replace the last element.

def replace_last_value(lst, value):
    return [t[:-1] + (value,) for t in lst]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!