When it is required to modify the list of tuple, the 'zip' method and the list comprehension can be used.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration for the same −
Example
my_list_1 = [('Hi', 1), ('there', 2), ('Jane', 3)] my_list_2 = [45, 67, 21] print("The first list is : ") print(my_list_1) print("The second list is : " ) print(my_list_2) my_result = [(i[0], j) for i, j in zip(my_list_1, my_list_2)] print("The modified list of tuple is : ") print(my_result)
Output
The first list is : [('Hi', 1), ('there', 2), ('Jane', 3)] The second list is : [45, 67, 21] The modified list of tuple is : [('Hi', 45), ('there', 67), ('Jane', 21)]
Explanation
- A list of tuple is defined, and is displayed on the console.
- Another list is defined, and is displayed on the console.
- Both these lists are zipped, and iterated over.
- It is then converted to a list.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.