Q:

Python program to update each element in the tuple list

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Updating Each element in Tuple List

In this problem, we are given a list of tuples and an adder element to be added to each element of the list. Our program will be adding the element to each element of the tuple list.

Input:
[(12, 8), (5, 2), (1, 3, 7, 8)]
ele = 6

Output:
[(18, 14), (11, 8), (7, 9, 13, 14)]

We simply need to take each element of the list of tuples and add the given element to it. Multiple ways are used which we can perform the task, let explore them.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by list comprehension to iterator the list of tuples and updating each element by adding the update element to it and then returning the updated list.

# Initializing and printing the list of tuples 

tupList = [(12, 8), (5, 2), (1, 3, 7, 8)]

print("The elements of list of tuple are " + str(tupList))
updateVal = 6

# Updating list of tuple by adding the given element
updatedList = [tuple(j + updateVal for j in tup ) for tup in tupList]

print("List after adding the update element to each element : " + str(updatedList))

Output:

The elements of list of tuple are [(12, 8), (5, 2), (1, 3, 7, 8)]
List after adding the update element to each element : [(18, 14), (11, 8), (7, 9, 13, 14)]

Method 2:

Another method to solve the problem is by using the map method to update the values using a lambda function that takes each element of tuple and added updateVal to it. All the updated map values are converted to a tuple using the tuple() method and encapsulated in a list.

# Initializing and printing the list of tuples

tupList = [(12, 8), (5, 2), (1, 3, 7, 8)]

print("The elements of list of tuple are " + str(tupList))
updateVal = 6

# Updating list of tuple by adding the given element
updatedList = [tuple(ele + updateVal for ele in tup ) for tup in tupList]

print("List after adding the update element to each element : " + str(updatedList))

Output:

The elements of list of tuple are [(12, 8), (5, 2), (1, 3, 7, 8)]
List after adding the update element to each element : [(18, 14), (11, 8), (7, 9, 13, 14)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to multiply adjacent elements of a ... >>
<< Python program to add a dictionary to tuple...