A list containing tuple of numbers is given as a input to your Python program your task is to to find the end item (Number) of each tuple and replace it with new value
Lets declare a list of tuples inside the program.
Write a Python Program to Replace Last Value of Tuples in a List
List containing three tuples are shown below and assign it to a variable.
tuples_list = [(23, 45, 20, 90), (12, 22, 83), (1, 2, 3, 4, 5)]
Using the for loop let's iterate all the tuple items present in the list and also use the enumerate to get the index of the tuple.
Using the if statement check if the instance is of tuple then frame a new tuple by removing the end item using [:-1] and append the (99,) to the new tuple. Assign the new tuple to the index of the list. Finally using the print function call print the list containing tuples.
for index, tuple_item in enumerate(tuples_list):
if isinstance(tuple_item, tuple):
new_tuple = tuple_item[:-1] + (99,)
tuples_list[index] = new_tuple
print(tuples_list)
Complete program
====================
tuples_list = [(23, 45, 20, 90), (12, 22, 83), (1, 2, 3, 4, 5)]
for index, tuple_item in enumerate(tuples_list):
if isinstance(tuple_item, tuple):
new_tuple = tuple_item[:-1] + (99,)
tuples_list[index] = new_tuple
print(tuples_list)
OUTPUT
===============
[(23, 45, 20, 99), (12, 22, 99), (1, 2, 3, 4, 99)]
Write a Python Program to Replace First Value of Tuples in a List
In the about us we are trying to replace the last value of each tuple but in the below program let's replace the first item with 99.
Let's take a list containing a tuple of integers as shown below it contains three tuples inside the list.
tuples_list = [(23, 45, 20, 90), (12, 22, 83), (1, 2, 3, 4, 5)]
Using the following, iterate all the lists containing tuples and also any enumerate to get the index of each tuple.
Using the if statement check if the instance is of type tuple and frame a new tuple by removing the first item [1:] and adding (99,) as the first tuple item. Assign the new tuple to list by using the index . Using print function call print the list of tuples.
for index, tuple_item in enumerate(tuples_list):
if isinstance(tuple_item, tuple):
new_tuple = (99,) + tuple_item[1:]
tuples_list[index] = new_tuple
print(tuples_list)
Complete working Code
===========================
tuples_list = [(23, 45, 20, 90), (12, 22, 83), (1, 2, 3, 4, 5)]
for index, tuple_item in enumerate(tuples_list):
if isinstance(tuple_item, tuple):
new_tuple = (99,) + tuple_item[1:]
tuples_list[index] = new_tuple
print(tuples_list)
Output
===================
[(99, 45, 20, 90), (99, 22, 83), (99, 2, 3, 4, 5)]
Conclusion
=============
Try executing the above program by replacing the integers present in the tuple and note down the results.
Comment down below if you have any suggestions or queries regarding the above program
0 Comments