When it is required to update every element in a tuple list (i.e list of tuples), list comprehension can be used.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration of the same −
Example
my_list_1 = [(7, 8, 0), (3, 45, 3), (2, 22,4)]
print ("The list of tuple is : " )
print(my_list_1)
element_to_add = 41
my_result = [tuple(j + element_to_add for j in sub ) for sub in my_list_1]
print("List of tuple after update is : ")
print(my_result)Output
The list of tuple is : [(7, 8, 0), (3, 45, 3), (2, 22, 4)] List of tuple after update is : [(48, 49, 41), (44, 86, 44), (43, 63, 45)]
Explanation
- A list of tuple is defined, and is displayed on the console.
- An element that needs to be added to the list of tuple is defined.
- This list of tuple is iterated over, and the element is added to every tuple in the list of tuples.
- This result is assigned to a value.
- It is displayed as output on the console.